Skip to content

Instantly share code, notes, and snippets.

View Kir-Antipov's full-sized avatar
🇺🇦
Stop the fucking war

Kir_Antipov Kir-Antipov

🇺🇦
Stop the fucking war
View GitHub Profile
@Kir-Antipov
Kir-Antipov / TypeExtensions.cs
Created February 19, 2019 08:19
Quick check whether the object implements the interface
// It's twice slower then `Obj is IMyInterface`
// But it's twice faster then any other check
// Based on my SO answer: https://ru.stackoverflow.com/a/945958/248572
public static bool Implements(object Obj, Type InterfaceType)
{
unsafe
{
// MT Pointer of our interface
IntPtr iMTPointer = InterfaceType.TypeHandle.Value;
@Kir-Antipov
Kir-Antipov / TypeExtensions.cs
Created February 19, 2019 08:24
Quick check whether the object implements the interface
// It's twice slower then `Obj is IMyInterface`
// But it's twice faster then any other check
// Based on my SO answer: https://ru.stackoverflow.com/a/945958/248572
public static bool Implements(Type ObjectType, Type InterfaceType)
{
unsafe
{
IntPtr iMTPointer = InterfaceType.TypeHandle.Value;
void* methodTable = ObjectType.TypeHandle.Value.ToPointer();
@Kir-Antipov
Kir-Antipov / TypeExtensions.cs
Last active January 12, 2021 07:23
Get the interfaces implemented by the object
// A little bit faster then standard Type.GetInterfaces()
public static Type[] GetInterfaces(Type ObjectType)
{
unsafe
{
void* methodTable = ObjectType.TypeHandle.Value.ToPointer();
int count = ((ushort*)methodTable)[7];
IntPtr* interfaces = (IntPtr*)((IntPtr*)methodTable)[9].ToPointer();
@Kir-Antipov
Kir-Antipov / TypeExtensions.cs
Last active January 12, 2021 07:22
Get the interfaces implemented by the object
// A little bit faster then standard Type.GetInterfaces()
public static Type[] GetInterfaces(object Obj)
{
unsafe
{
TypedReference trObj = __makeref(Obj);
IntPtr ptrObj = **(IntPtr**)&trObj;
void* methodTable = (*(IntPtr*)ptrObj.ToPointer()).ToPointer();
@Kir-Antipov
Kir-Antipov / Other.cs
Created February 19, 2019 08:57
Get object's pointer
object obj = new List<int> { 1, 2, 3 };
TypedReference trObj = __makeref(obj);
IntPtr ptrObj = **(IntPtr**)&trObj;
@Kir-Antipov
Kir-Antipov / void.cs
Created July 15, 2019 09:58
How to create an object of type void
public class MyVoid
{
public static readonly MyVoid Instance = new MyVoid();
private MyVoid()
{
unsafe
{
MyVoid it = this;
TypedReference typedReference = __makeref(it);
@Kir-Antipov
Kir-Antipov / totp.cs
Created August 23, 2019 22:02
Quick check of 6-digit totp code
public static bool Verify(string digits, string secret)
{
if (string.IsNullOrEmpty(digits) || string.IsNullOrEmpty(secret))
return false;
long iterations = DateTimeOffset.Now.ToUnixTimeSeconds() / 30L;
byte[] secretBytes = Base32ToBytes(secret);
if (Verify(digits, secretBytes, iterations))
return true;
else