public static bool SetEquals <T>(ISet <T> set, IEnumerable <T> other) #endif { #region CONTRACT #if DEBUG Contract.Assert(set != null, "set != null"); #endif // DEBUG if (other == null) { throw new ArgumentNullException("other"); } #endregion CONTRACT if (set.Count == 0) { var asCollection = other as ICollection <T>; if (asCollection != null) { return(asCollection.Count == 0); } } // Cannot use other.All() here because it always returns true for empty source. #if NETFX_35 var asSet = other as HashSet <T> ?? new HashSet <T>(other); #else var asSet = other as ISet <T> ?? new HashSet <T>(other); #endif int matchCount = 0; foreach (var item in asSet) { if (!set.Contains(item)) { return(false); } else { matchCount++; } } return(matchCount == set.Count); }
/// <summary> /// Unpacks <see cref="String"/> value from the specified <see cref="Stream"/> with specified encoding. /// </summary> /// <param name="source">The <see cref="Stream"/> which contains Message Pack binary stream.</param> /// <param name="encoding">The <see cref="Encoding"/> to decode binary stream.</param> /// <returns> /// The unpacked <see cref="String"/> value. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <c>null</c>. /// Or <paramref name="encoding"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The <see cref="P:Stream.CanRead"/> of <paramref name="source"/> is <c>false</c>. /// </exception> /// <exception cref="UnpackException"> /// <paramref name="source"/> is not valid MessagePack stream. /// Note that the state of <paramref name="source"/> will be unpredictable espicially it is not seekable. /// </exception> /// <exception cref="MessageTypeException"> /// The unpacked result in the <paramref name="source"/> is not raw binary. /// Or, the unpacked result in the <paramref name="source"/> is invalid as specified encoding byte stream. /// Note that the state of <paramref name="source"/> will be unpredictable espicially it is not seekable. /// </exception> /// <remarks> /// <para> /// The processed bytes count can be calculated via <see cref="P:Stream.Position"/> of <paramref name="source"/> when the <see cref="P:Stream.CanSeek" /> is <c>true</c>. /// </para> /// <para> /// When the type of packed value is not known, use <see cref="UnpackObject(Stream)"/> instead. /// </para> /// </remarks> public static string UnpackString(Stream source, Encoding encoding) { if (encoding == null) { throw new ArgumentNullException("encoding"); } Contract.EndContractBlock(); try { var result = UnpackBinary(source); return(encoding.GetString(result, 0, result.Length)); } catch (DecoderFallbackException ex) { throw NewInvalidEncodingException(encoding, ex); } }
/// <summary> /// Unpacks <see cref="String" /> value from specified offsetted byte array with specified encoding. /// </summary> /// <param name="source">The byte array which contains Message Pack binary stream.</param> /// <param name="offset">The offset to be unpacking start with.</param> /// <param name="encoding">The <see cref="Encoding"/> to decode binary stream.</param> /// <returns> /// The <see cref="UnpackingResult{T}"/> of <see cref="String" /> which contains unpacked <see cref="String" /> value and processed bytes count. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <c>null</c>. /// Or, <paramref name="encoding"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="source"/> is empty. /// Or, the length of <paramref name="source"/> is not greater than <paramref name="offset"/>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is negative value. /// </exception> /// <exception cref="UnpackException"> /// <paramref name="source"/> is not valid MessagePack stream. /// </exception> /// <exception cref="MessageTypeException"> /// The unpacked result in the <paramref name="source"/> is not compatible to <see cref="String" />. /// Or, the unpacked result in the <paramref name="source"/> is invalid as specified encoding byte stream. /// </exception> /// <remarks> /// <para> /// Invocation of this method is equivalant to call <see cref="UnpackString(byte[], int)"/> with <c>offset</c> is <c>0</c>. /// </para> /// <para> /// When the type of packed value is not known, use <see cref="UnpackObject(byte[])"/> instead. /// </para> /// </remarks> public static UnpackingResult <string> UnpackString(byte[] source, int offset, Encoding encoding) { if (encoding == null) { throw new ArgumentNullException("encoding"); } Contract.EndContractBlock(); try { var result = UnpackBinary(source, offset); return(new UnpackingResult <string>(encoding.GetString(result.Value, 0, result.Value.Length), result.ReadCount)); } catch (DecoderFallbackException ex) { throw NewInvalidEncodingException(encoding, ex); } }
public static string GetFullName(this Type source) { #if !UNITY Contract.Assert(source != null, "source != null"); #endif // !UNITY if (source.IsArray) { var elementType = source.GetElementType(); if (!elementType.GetIsGenericType()) { return(source.FullName); } if (1 < source.GetArrayRank()) { return(elementType.GetFullName() + "[*]"); } else { return(elementType.GetFullName() + "[]"); } } if (!source.GetIsGenericType()) { return(source.FullName); } return (String.Concat( source.Namespace, ReflectionAbstractions.TypeDelimiter, source.Name, '[', #if !NETFX_35 && !UNITY String.Join(", ", source.GetGenericArguments().Select(t => t.GetFullName())), #else String.Join(", ", source.GetGenericArguments().Select(t => t.GetFullName()).ToArray()), #endif // !NETFX_35 && !UNITY ']' )); }
/// <summary> /// Unpacks specified type value with the specified context. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="source">The <see cref="Unpacker"/>.</param> /// <param name="context">The <see cref="SerializationContext"/> holds shared serializers.</param> /// <returns>The deserialized value.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <c>null</c>. /// Or <paramref name="context"/> is <c>null</c>. /// </exception> /// <exception cref="System.Runtime.Serialization.SerializationException"> /// Cannot deserialize <typeparamref name="T"/> value. /// </exception> public static T Unpack <T>(this Unpacker source, SerializationContext context) { if (source == null) { throw new ArgumentNullException("source"); } if (context == null) { throw new ArgumentNullException("context"); } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY return(UnpackCore <T>(source, context)); }
/// <summary> /// Emit array initialization code with initializer. /// Post condition is evaluation stack will no be modified as previous state. /// Note that initialized array is not placed on the top of evaluation stack. /// </summary> /// <param name="arrayLoadingEmitter"> /// Delegate to emittion of array loading instruction. /// 1st argument is this instance. /// Post condition is that exactly one target array will be added on the top of stack and element type is <paramref name="elementType"/>. /// </param> /// <param name="arrayStoringEmitter"> /// Delegate to emittion of array storing instruction. /// 1st argument is this instance. /// Pre condition is that the top of evaluation stack is array type and its element type is <paramref name="elementType"/>. /// Post condition is that exactly one target array will be removed from the top of stack. /// </param> /// <param name="elementType"><see cref="Type"/> of array element. This can be generaic parameter.</param> /// <param name="elementLoadingEmitters"> /// List of delegates to emittion of storing element loading instruction. /// Index of this array corresponds to index of initializing array. /// 1st argument is this instance. /// Post condition is that exactly one storing element will be added on the top of stack and its type is <paramref name="elementType"/> compatible. /// </param> public void EmitNewarr(Action <TracingILGenerator> arrayLoadingEmitter, Action <TracingILGenerator> arrayStoringEmitter, Type elementType, params Action <TracingILGenerator>[] elementLoadingEmitters) { Contract.Assert(arrayLoadingEmitter != null); Contract.Assert(arrayStoringEmitter != null); Contract.Assert(elementType != null); Contract.Assert(elementLoadingEmitters != null); Contract.Assert(Contract.ForAll(elementLoadingEmitters, item => item != null)); // TODO: NLiblet this.EmitNewarrCore(elementType, elementLoadingEmitters.Length); arrayStoringEmitter(this); // TODO: NLiblet for (long i = 0; i < elementLoadingEmitters.Length; i++) { arrayLoadingEmitter(this); this.EmitAnyStelem(elementType, null, i, elementLoadingEmitters[i]); } }
/// <summary> /// Packs specified value with the specified context. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="source">The <see cref="Packer"/>.</param> /// <param name="value">The value to be serialized.</param> /// <param name="context">The <see cref="SerializationContext"/> holds shared serializers.</param> /// <returns><paramref name="source"/>.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="source"/> is <c>null</c>. /// Or <paramref name="context"/> is <c>null</c>. /// </exception> /// <exception cref="System.Runtime.Serialization.SerializationException"> /// Cannot serialize <paramref name="value"/>. /// </exception> public static Packer Pack <T>(this Packer source, T value, SerializationContext context) { if (source == null) { throw new ArgumentNullException("source"); } if (context == null) { throw new ArgumentNullException("context"); } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY PackCore(source, value, context); return(source); }
public static bool Overlaps <T>(ISet <T> set, IEnumerable <T> other) #endif { #region CONTRACT Contract.Assert(set != null, "set != null"); if (other == null) { throw new ArgumentNullException("other"); } #endregion CONTRACT if (set.Count == 0) { return(false); } return(other.Any(item => set.Contains(item))); }
protected internal override void PackToCore(Packer packer, DateTimeOffset objectTree) { if (this._conversion == DateTimeConversionMethod.Native) { packer.PackArrayHeader(2); packer.Pack(objectTree.DateTime.ToBinary()); unchecked { packer.Pack(( short )(objectTree.Offset.Hours * 60 + objectTree.Offset.Minutes)); } } else { #if DEBUG Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc); #endif // DEBUG packer.Pack(MessagePackConvert.FromDateTimeOffset(objectTree)); } }
/// <summary> /// Initializes an empty new instance of the <see cref="MessagePackObjectDictionary"/> class with specified initial capacity. /// </summary> /// <param name="initialCapacity">The initial capacity.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="initialCapacity"/> is negative. /// </exception> /// <remarks> /// This operation is an O(1) operation. /// </remarks> public MessagePackObjectDictionary(int initialCapacity) { if (initialCapacity < 0) { throw new ArgumentOutOfRangeException("initialCapacity"); } Contract.EndContractBlock(); if (initialCapacity <= Threashold) { this._keys = new List <MessagePackObject>(initialCapacity); this._values = new List <MessagePackObject>(initialCapacity); } else { this._dictionary = new Dictionary <MessagePackObject, MessagePackObject>(initialCapacity, MessagePackObjectEqualityComparer.Instance); } }
private static void GetTupleItemTypes(IList <Type> itemTypes, IList <Type> result) { var count = itemTypes.Count == 8 ? 7 : itemTypes.Count; for (var i = 0; i < count; i++) { result.Add(itemTypes[i]); } if (itemTypes.Count == 8) { var trest = itemTypes[7]; #if DEBUG Contract.Assert(IsTuple(trest), "IsTuple( " + trest.AssemblyQualifiedName + " )"); #endif // DEBUG // Put nested tuple's item types recursively. GetTupleItemTypes(trest.GetGenericArguments(), result); } }
private static IEnumerable <Func <T, Object> > GetGetters(IList <Type> itemTypes, IList <Type> tupleTypes) { var depth = -1; var propertyInvocationChain = new List <PropertyInfo>(itemTypes.Count % 7 + 1); for (int i = 0; i < itemTypes.Count; i++) { if (i % 7 == 0) { depth++; } for (int j = 0; j < depth; j++) { // .TRest.TRest ... var restProperty = tupleTypes[j].GetProperty("Rest"); Contract.Assert(restProperty != null, "restProperty != null"); propertyInvocationChain.Add(restProperty); } var itemNProperty = tupleTypes[depth].GetProperty("Item" + ((i % 7) + 1)); propertyInvocationChain.Add(itemNProperty); #if DEBUG Contract.Assert( itemNProperty != null, tupleTypes[depth].GetFullName() + "::Item" + ((i % 7) + 1) + " [ " + depth + " ] @ " + i); #endif // DEBUG var getters = propertyInvocationChain.Select(property => property.GetGetMethod()).ToArray(); yield return (tuple => { object current = tuple; foreach (var getter in getters) { current = getter.InvokePreservingExceptionType(current); } return current; }); propertyInvocationChain.Clear(); } }
private static async Task PackToArrayAsyncCore <TObject>( Packer packer, TObject target, IList <Func <Packer, TObject, CancellationToken, Task> > operations, CancellationToken cancellationToken ) { #if ASSERT Contract.Assert(packer != null); Contract.Assert(operations != null); #endif // ASSERT await packer.PackArrayHeaderAsync(operations.Count, cancellationToken).ConfigureAwait(false); foreach (var operation in operations) { await operation(packer, target, cancellationToken).ConfigureAwait(false); } }
public MessagePackSerializer Get( SerializationContext context, Type targetType, object providerParameter ) { #if UNITY MethodInfo method; if ( !this._cache.TryGetValue( targetType.TypeHandle, out method ) || method == null ) { method = GetSerializer1Method.MakeGenericMethod( targetType ); this._cache[ targetType.TypeHandle ] = method; } return ( MessagePackSerializer )method.InvokePreservingExceptionType( context, providerParameter ); #else Func<SerializationContext, object, MessagePackSerializer> func; #if !FEATURE_CONCURRENT lock ( this._cache ) { #endif // !FEATURE_CONCURRENT if ( !this._cache.TryGetValue( targetType.TypeHandle, out func ) || func == null ) { #if !NETSTANDARD1_1 && !NETSTANDARD1_3 func = Delegate.CreateDelegate( typeof( Func<SerializationContext, object, MessagePackSerializer> ), typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetMethod( "Get" ) ) as Func<SerializationContext, object, MessagePackSerializer>; #else func = typeof( SerializerGetter<> ).MakeGenericType( targetType ).GetMethod( "Get" ).CreateDelegate( typeof( Func<SerializationContext, object, MessagePackSerializer> ) ) as Func<SerializationContext, object, MessagePackSerializer>; #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 Contract.Assert( func != null, "func != null" ); this._cache[ targetType.TypeHandle ] = func; } #if !FEATURE_CONCURRENT } #endif // !FEATURE_CONCURRENT return func( context, providerParameter ); #endif // UNITY }
/// <summary> /// Determines whether the <see cref="MessagePackObjectDictionary"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="MessagePackObjectDictionary"/>.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <returns> /// <c>true</c> if the <see cref="MessagePackObjectDictionary"/> contains an element with the key; otherwise, <c>false</c>. /// </returns> /// <remarks> /// This method approaches an O(1) operation. /// </remarks> public bool ContainsKey(MessagePackObject key) { if (key.IsNil) { ThrowKeyNotNilException("key"); } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY #if !UNITY this.AssertInvariant(); #endif // !UNITY return (this._dictionary == null ? this._keys.Contains(key, MessagePackObjectEqualityComparer.Instance) : this._dictionary.ContainsKey(key)); }
private static IEnumerable <SerializingMember> GetTargetMembers(Type type) { Contract.Assert(type != null, "type != null"); var members = GetDistinctMembers(type); var filtered = members.Where(item => item.GetCustomAttributesData().Any(a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName)).ToArray(); if (filtered.Length > 0) { return(GetAnnotatedMembersWithDuplicationDetection(type, filtered)); } if (type.GetCustomAttributesData().Any(attr => attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute")) { return(GetSystemRuntimeSerializationCompatibleMembers(members)); } return(GetPublicUnpreventedMembers(members)); }
protected void BuildEnumSerializer(TContext context) { #if DEBUG Contract.Assert(this.TargetType.GetIsEnum()); #endif // DEBUG var underlyingType = Enum.GetUnderlyingType(this.TargetType); #if DEBUG Contract.Assert(underlyingType != null, "Underlying type of " + this.TargetType + " is null."); #endif // DEBUG this.BuildPackUnderlyingValueTo(context, underlyingType, false); this.BuildUnpackFromUnderlyingValue(context, underlyingType); #if FEATURE_TAP if (this.WithAsync(context)) { this.BuildPackUnderlyingValueTo(context, underlyingType, true); } #endif // FEATURE_TAP }
void IDictionary.Remove(object key) { if (key == null) { throw new ArgumentNullException("key"); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); var typedKey = ValidateObjectArgument(key, "key"); if (typedKey.IsNil) { ThrowKeyNotNilException("key"); } this.RemoveCore(typedKey, default(MessagePackObject), false); }
void IDictionary.Add(object key, object value) { if (key == null) { throw new ArgumentNullException("key"); } this.VerifyIsNotFrozen(); Contract.EndContractBlock(); var typedKey = ValidateObjectArgument(key, "key"); if (typedKey.IsNil) { ThrowKeyNotNilException("key"); } this.AddCore(typedKey, ValidateObjectArgument(value, "value"), false); }
private static IEnumerable <Func <T, object> > GetGetters <TInfo, TAccessor>( IList <Type> itemTypes, IList <Type> tupleTypes, Func <Type, string, TInfo> metadataFactory, Func <TInfo, TAccessor> accessorFactory, Func <IEnumerable <TAccessor>, Func <T, object> > chainedGetterFactory ) { var depth = -1; var memberInvocationChain = new List <TInfo>(itemTypes.Count % 7 + 1); for (var i = 0; i < itemTypes.Count; i++) { if (i % 7 == 0) { depth++; } for (var j = 0; j < depth; j++) { // .TRest.TRest ... var restMember = metadataFactory(tupleTypes[j], "Rest"); #if DEBUG Contract.Assert(restMember != null, "restMember != null"); #endif // DEBUG memberInvocationChain.Add(restMember); } var itemNMember = metadataFactory(tupleTypes[depth], "Item" + ((i % 7) + 1)); memberInvocationChain.Add(itemNMember); #if DEBUG Contract.Assert( itemNMember != null, tupleTypes[depth].GetFullName() + "::Item" + ((i % 7) + 1) + " [ " + depth + " ] @ " + i); #endif // DEBUG var getters = memberInvocationChain.Select(accessorFactory).ToArray(); yield return(chainedGetterFactory(getters)); memberInvocationChain.Clear(); } }
protected internal override async Task PackToAsyncCore(Packer packer, DateTimeOffset objectTree, CancellationToken cancellationToken) { if (this._conversion == DateTimeConversionMethod.Native) { await packer.PackArrayHeaderAsync(2, cancellationToken).ConfigureAwait(false); await packer.PackAsync(objectTree.DateTime.ToBinary(), cancellationToken).ConfigureAwait(false); unchecked { await packer.PackAsync(( short )(objectTree.Offset.Hours * 60 + objectTree.Offset.Minutes), cancellationToken).ConfigureAwait(false); } } else { #if DEBUG Contract.Assert(this._conversion == DateTimeConversionMethod.UnixEpoc); #endif // DEBUG await packer.PackAsync(MessagePackConvert.FromDateTimeOffset(objectTree), cancellationToken).ConfigureAwait(false); } }
private void ThrowUnexpectedExtCodeException(ReadValueResult type) { #if DEBUG Contract.Assert(false, "Unexpected ext-code type:" + type); #endif // DEBUG // ReSharper disable HeuristicUnreachableCode long offsetOrPosition; var isRealOffset = this.GetPreviousPosition(out offsetOrPosition); throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, isRealOffset ? "Unexpeded ext-code type {0} at position {1:#,0}" : "Unexpeded ext-code type {0} at offset {1:#,0}", type, offsetOrPosition ) ); // ReSharper restore HeuristicUnreachableCode }
public static string GetName(this Type source) { Contract.Assert(source != null, "source != null"); if (!source.GetIsGenericType()) { return(source.Name); } return (String.Concat( source.Name, '[', #if !NETFX_35 && !UNITY String.Join(", ", source.GetGenericArguments().Select(t => t.GetName())), #else String.Join(", ", source.GetGenericArguments().Select(t => t.GetName()).ToArray()), #endif // !NETFX_35 && !UNITY ']' )); }
public static void Encode(Packer packer, Type type) { var assemblyName = #if !SILVERLIGHT type.GetAssembly().GetName(); #else new AssemblyName(type.GetAssembly().FullName); #endif // !SILVERLIGHT #if DEBUG && !UNITY Contract.Assert(type.Namespace != null, "type.Namespace != null"); #endif // DEBUG && !UNITY packer.PackArrayHeader(2); packer.PackArrayHeader(6); packer.Pack(( byte )TypeInfoEncoding.RawCompressed); // Omit namespace prefix when it equals to declaring assembly simple name. var compressedTypeName = type.Namespace.StartsWith(assemblyName.Name, StringComparison.Ordinal) ? Elipsis + type.FullName.Substring(assemblyName.Name.Length + 1) : type.FullName; var version = new byte[16]; Buffer.BlockCopy(BitConverter.GetBytes(assemblyName.Version.Major), 0, version, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(assemblyName.Version.Minor), 0, version, 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(assemblyName.Version.Build), 0, version, 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(assemblyName.Version.Revision), 0, version, 12, 4); packer .Pack(compressedTypeName) .Pack(assemblyName.Name) .Pack(version) #if !XAMIOS && !XAMDROID .Pack(assemblyName.GetCultureName()) #else .Pack(assemblyName.GetCultureName() == "neutral" ? null : assemblyName.GetCultureName()) #endif // !XAMIOS && !XAMDROID .Pack(assemblyName.GetPublicKeyToken()); }
public MessagePackSerializer BuildSerializerInstance(SerializationContext context, Type concreteType, PolymorphismSchema schema) { #if DEBUG Contract.Assert( this.CollectionTraits.DetailedCollectionType != CollectionDetailedKind.Array, this.TargetType + "(" + this.CollectionTraits.DetailedCollectionType + ") != CollectionDetailedKind.Array" ); #endif // DEBUG Func <SerializationContext, MessagePackSerializer> constructor; var codeGenerationContext = this.CreateCodeGenerationContextForSerializerCreation(context); if (this.TargetType.GetIsEnum()) { this.BuildEnumSerializer(codeGenerationContext); constructor = this.CreateEnumSerializerConstructor(codeGenerationContext); } else { SerializationTarget targetInfo; this.BuildSerializer(codeGenerationContext, concreteType, schema, out targetInfo); constructor = this.CreateSerializerConstructor( codeGenerationContext, targetInfo, schema, targetInfo == null ? default(SerializerCapabilities? ) : targetInfo.GetCapabilitiesForObject() ); } if (constructor != null) { var serializer = constructor(context); #if DEBUG Contract.Assert(serializer != null); #endif // DEBUG return(serializer); } throw SerializationExceptions.NewTypeCannotSerialize(this.TargetType); }
private async Task ReadStrictAsync(byte[] buffer, int size, CancellationToken cancellationToken) { #if DEBUG if (this._source.CanSeek) { Contract.Assert(this._source.Position == this._offset, this._source.Position + "==" + this._offset); } #endif // DEBUG // Reading 0 byte from stream causes exception in some implementation (issue #60, reported from @odyth). if (size == 0) { return; } this._lastOffset = this._offset; var remaining = size; var offset = 0; int read; do { read = await this._source.ReadAsync(buffer, offset, remaining, cancellationToken).ConfigureAwait(false); remaining -= read; offset += read; } while (read > 0 && remaining > 0); this._offset += offset; #if DEBUG if (this._source.CanSeek) { Contract.Assert(this._source.Position == this._offset, this._source.Position + "==" + this._offset); } #endif // DEBUG if (offset < size) { this.ThrowEofException(size); } }
private SubtreeUnpacker(ItemsUnpacker root, SubtreeUnpacker parent) { #if DEBUG && !UNITY Contract.Assert(root != null, "root != null"); Contract.Assert(root.IsArrayHeader || root.IsMapHeader, "root.IsArrayHeader || root.IsMapHeader"); #endif // DEBUG && !UNITY this._root = root; this._parent = parent; this._unpacked = new Int64Stack(2); this._itemsCount = new Int64Stack(2); this._isMap = new BooleanStack(2); if (root.ItemsCount > 0) { this._itemsCount.Push(root.InternalItemsCount * (( int )root.InternalCollectionType)); this._unpacked.Push(0); this._isMap.Push(root.InternalCollectionType == ItemsUnpacker.CollectionType.Map); } this._state = State.InHead; }
/// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <value> /// The element with the specified key. /// </value> /// <param name="key">Key for geting or seting value.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>. /// </exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException"> /// The property is retrieved and <paramref name="key"/> is not found. /// </exception> /// <exception cref="InvalidOperationException"> /// The property is set and this instance is frozen. /// </exception> /// <remarks> /// <para> /// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>, /// and UTF-8 encoded bytes are considered equals to <see cref="String"/>. /// </para> /// <para> /// This method approaches an O(1) operation. /// </para> /// </remarks> public MessagePackObject this[MessagePackObject key] { get { if (key.IsNil) { ThrowKeyNotNilException("key"); } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY MessagePackObject result; if (!this.TryGetValue(key, out result)) { throw new KeyNotFoundException(String.Format(CultureInfo.CurrentCulture, "Key '{0}'({1} type) does not exist in this dictionary.", key, key.UnderlyingType)); } return(result); } set { if (key.IsNil) { ThrowKeyNotNilException("key"); } this.VerifyIsNotFrozen(); #if !UNITY Contract.EndContractBlock(); this.AssertInvariant(); #endif // !UNITY this.AddCore(key, value, true); } }
/// <summary> /// Copies a range of elements from this collection to a compatible one-dimensional array, /// starting at the specified index of the target array. /// </summary> /// <param name="index"> /// The zero-based index in the source dictionary at which copying begins. /// </param> /// <param name="array"> /// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this dictionary. /// The <see cref="Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex"> /// The zero-based index in <paramref name="array"/> at which copying begins. /// </param> /// <param name="count"> /// The number of elements to copy. /// </param> public void CopyTo(int index, MessagePackObject[] array, int arrayIndex, int count) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (0 < this.Count && this.Count <= index) { throw new ArgumentException("Specified array is too small to complete copy operation.", "array"); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (array.Length - count <= arrayIndex) { throw new ArgumentException("Specified array is too small to complete copy operation.", "array"); } #if !UNITY Contract.EndContractBlock(); #endif // !UNITY CollectionOperation.CopyTo(this, this.Count, index, array, arrayIndex, count); }
private static void VerifyNilImplication(Type type, IEnumerable <SerializingMember> entries) { foreach (var serializingMember in entries) { if (serializingMember.Contract.NilImplication == NilImplication.Null) { var itemType = serializingMember.Member.GetMemberValueType(); if (itemType != typeof(MessagePackObject) && itemType.GetIsValueType() && Nullable.GetUnderlyingType(itemType) == null) { SerializationExceptions.ThrowValueTypeCannotBeNull(serializingMember.Member.ToString(), itemType, type); } bool isReadOnly; FieldInfo asField; PropertyInfo asProperty; if ((asField = serializingMember.Member as FieldInfo) != null) { isReadOnly = asField.IsInitOnly; } else { asProperty = serializingMember.Member as PropertyInfo; #if DEBUG Contract.Assert(asProperty != null, serializingMember.Member.ToString()); #endif // DEBUG isReadOnly = asProperty.GetSetMethod() == null; } if (isReadOnly) { SerializationExceptions.ThrowNullIsProhibited(serializingMember.Member.ToString()); } } } }