Skip to content

Instantly share code, notes, and snippets.

@graffic
Created November 29, 2011 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graffic/1404782 to your computer and use it in GitHub Desktop.
Save graffic/1404782 to your computer and use it in GitHub Desktop.
Dictionaries to Map in MessagePack for .NET
if (type.IsMap())
{
Label work = il.DefineLabel();
Label getNext = il.DefineLabel();
Label end = il.DefineLabel();
il.EmitLd(arg_writer);
// 1. Get length of the dictionary
il.EmitLd(arg_obj);
il.Emit(OpCodes.Callvirt, typeof(System.Collections.ICollection).GetMethod("get_Count"));
// 2. Write dictionary header
il.Emit(OpCodes.Callvirt, typeof(MsgPackWriter).GetMethod("WriteMapHeader", new Type[] { typeof(int) }));
// 3. Loop each member.
// 3.1. Get The enumerator
il.EmitLd(arg_obj);
il.Emit(OpCodes.Callvirt, typeof(System.Collections.IDictionary).GetMethod("GetEnumerator"));
il.EmitSt(local_enumerator);
var foreachblocklabel = il.BeginExceptionBlock();
il.Emit(OpCodes.Br_S, getNext);
il.MarkLabel(work);
// 3.x Extract the element
il.EmitLd(local_enumerator);
il.Emit(OpCodes.Callvirt, typeof(IDictionaryEnumerator).GetProperty("Key").GetGetMethod());
il.EmitSt(local_keyvalue);
EmitPackMemberValueCode(type.GetGenericArguments()[0], il, arg_writer, local_keyvalue, null, null, type, mi, lookupPackMethod);
il.EmitLd(local_enumerator);
il.Emit(OpCodes.Callvirt, typeof(IDictionaryEnumerator).GetProperty("Value").GetGetMethod());
il.EmitSt(local_keyvalue);
EmitPackMemberValueCode(type.GetGenericArguments()[1], il, arg_writer, local_keyvalue, null, null, type, mi, lookupPackMethod);
// 3.x GetNext
il.MarkLabel(getNext);
il.EmitLd(local_enumerator);
il.Emit(OpCodes.Callvirt, typeof(IEnumerator).GetMethod("MoveNext"));
il.Emit(OpCodes.Brtrue_S, work);
// 3.x Finish the loop
il.Emit(OpCodes.Leave, end);
il.BeginFinallyBlock();
il.EmitLd(local_enumerator);
il.Emit(OpCodes.Callvirt, typeof(IDisposable).GetMethod("Dispose"));
il.EndExceptionBlock();
il.MarkLabel(end);
goto FinallyProcess;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment