示例#1
0
        /// <summary>
        ///		Packs a null value to current stream asynchronously.
        /// </summary>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ObjectDisposedException">This instance has been disposed.</exception>
        public async Task PackNullAsync(CancellationToken cancellationToken)
        {
            this.VerifyNotDisposed();
            Contract.EndContractBlock();

            await this.PrivatePackNullAsyncCore(cancellationToken).ConfigureAwait(false);
        }
        /// <summary>
        ///		Initializes a new instance of the <see cref="MessagePackObjectDictionary"/> class.
        /// </summary>
        /// <param name="dictionary">The dictionary to be copied from.</param>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="dictionary"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///		Failed to copy from <paramref name="dictionary"/>.
        /// </exception>
        /// <remarks>
        ///		This constructor takes <em>O(N)</em> time, <em>N</em> is <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>.
        ///		Initial capacity will be <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>.
        /// </remarks>
        public MessagePackObjectDictionary(IDictionary <MessagePackObject, MessagePackObject> dictionary)
        {
            if (dictionary == null)
            {
                throw new ArgumentNullException("dictionary");
            }

            Contract.EndContractBlock();

            if (dictionary.Count <= Threashold)
            {
                this._keys   = new List <MessagePackObject>(dictionary.Count);
                this._values = new List <MessagePackObject>(dictionary.Count);
            }
            else
            {
                this._dictionary = new Dictionary <MessagePackObject, MessagePackObject>(dictionary.Count, MessagePackObjectEqualityComparer.Instance);
            }

            try
            {
                foreach (var kv in dictionary)
                {
                    this.AddCore(kv.Key, kv.Value, false);
                }
            }
            catch (ArgumentException ex)
            {
#if SILVERLIGHT
                throw new ArgumentException("Failed to copy specified dictionary.", ex);
#else
                throw new ArgumentException("Failed to copy specified dictionary.", "dictionary", ex);
#endif
            }
        }
        /// <summary>
        ///		Gets the value associated with the specified key.
        /// </summary>
        /// <param name="key">
        ///		The key whose value to get.
        ///	</param>
        /// <param name="value">
        ///		When this method returns, the value associated with the specified key, if the key is found;
        ///		otherwise, the default value for the type of the <paramref name="value"/> parameter.
        ///		This parameter is passed uninitialized.
        ///	</param>
        /// <returns>
        ///		<c>true</c> if this dictionary contains an element with the specified key; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
        /// </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 bool TryGetValue(MessagePackObject key, out MessagePackObject value)
        {
            if (key.IsNil)
            {
                ThrowKeyNotNilException("key");
            }

            Contract.EndContractBlock();
            this.AssertInvariant();

            if (this._dictionary == null)
            {
                int index = this._keys.FindIndex(item => item == key);
                if (index < 0)
                {
                    value = MessagePackObject.Nil;
                    return(false);
                }
                else
                {
                    value = this._values[index];
                    return(true);
                }
            }
            else
            {
                return(this._dictionary.TryGetValue(key, out value));
            }
        }
        ///	<summary>
        ///		Unpacks raw value from the specified <see cref="Stream"/> as <see cref="UnpackingStream"/>.
        ///	</summary>
        ///	<param name="source">The <see cref="Stream"/> which contains Message Pack binary stream.</param>
        ///	<returns>
        ///		The <see cref="UnpackingStream"/> which represents raw value stream.
        ///	</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="source"/> 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.
        ///		Note that the state of <paramref name="source"/> will be unpredictable espicially it is not seekable.
        ///	</exception>
        /// <remarks>
        ///		<para>
        ///			<see cref="UnpackingStream"/> does not own <paramref name="source"/>, so <paramref name="source"/> still should be closed.
        ///		</para>
        ///		<para>
        ///			When the type of packed value is not known, use <see cref="UnpackObject(Stream)"/> instead.
        ///		</para>
        ///	</remarks>
        public static UnpackingStream UnpackByteStream(Stream source)
        {
            ValidateStream(source);
            Contract.EndContractBlock();

            return(UnpackByteStreamCore(source));
        }
示例#5
0
        /// <summary>
        ///		Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">
        ///		An array of bytes. When this method returns,
        ///		the buffer contains the specified byte array with the values between <paramref name="offset"/> and ( <paramref name="offset"/> + <paramref name="count"/> - 1)
        ///		replaced by the bytes read from the current source.
        ///	</param>
        /// <param name="offset">
        ///		The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.
        /// </param>
        /// <param name="count">
        ///		The maximum number of bytes to be read from the current stream.
        /// </param>
        /// <returns>
        ///		The total number of bytes read into the buffer.
        ///		This can be less than the number of bytes requested if that many bytes are not currently available,
        ///		or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <exception cref="T:System.ArgumentException">
        ///		The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.
        ///	</exception>
        /// <exception cref="T:System.ArgumentNullException">
        ///		<paramref name="buffer"/> is <c>null</c>.
        ///	</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">
        ///		<paramref name="offset"/> or <paramref name="count"/> is negative.
        ///	</exception>
        /// <exception cref="T:System.IO.IOException">
        ///		An I/O error occurs.
        /// </exception>
        /// <exception cref="T:System.ObjectDisposedException">
        ///		Methods were called after the stream was closed.
        ///	</exception>
        /// <remarks>
        ///		<note>
        ///			Arguments might be passed to the underlying <see cref="Stream"/> without any validation.
        ///		</note>
        /// </remarks>
        public sealed override int Read(byte[] buffer, int offset, int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            Contract.EndContractBlock();

            if (this.CurrentOffset == this.RawLength)
            {
                return(0);
            }

            int realCount = count;
            var exceeds   = this.CurrentOffset + count - this.RawLength;

            if (exceeds > 0)
            {
                realCount -= checked (( int )exceeds);
            }

            var readCount = this.Underlying.Read(buffer, offset, realCount);

            this.CurrentOffset += readCount;
            return(readCount);
        }
        /// <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");
                }

                Contract.EndContractBlock();

                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();

                Contract.EndContractBlock();
                this.AssertInvariant();
                this.AddCore(key, value, true);
            }
        }
示例#7
0
        /// <summary>
        ///		Packs <see cref="Byte"/> value to current stream asynchronously.
        /// </summary>
        /// <param name="value"><see cref="Byte"/> value.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ObjectDisposedException">This instance has been disposed.</exception>
        public Task PackAsync(byte value, CancellationToken cancellationToken)
        {
            this.VerifyNotDisposed();
            Contract.EndContractBlock();

            return(this.PrivatePackAsyncCore(value, cancellationToken));
        }
示例#8
0
        /// <summary>
        ///		Packs <see cref="Byte"/> value to current stream.
        /// </summary>
        /// <param name="value"><see cref="Byte"/> value.</param>
        /// <returns>This instance.</returns>
        /// <exception cref="ObjectDisposedException">This instance has been disposed.</exception>
        public Packer Pack(byte value)
        {
            this.VerifyNotDisposed();
            Contract.EndContractBlock();

            this.PrivatePackCore(value);
            return(this);
        }
示例#9
0
        /// <summary>
        ///		Packs a null value to current stream.
        /// </summary>
        /// <returns>This instance.</returns>
        /// <exception cref="ObjectDisposedException">This instance has been disposed.</exception>
        public Packer PackNull()
        {
            this.VerifyNotDisposed();
            Contract.EndContractBlock();

            this.PrivatePackNullCore();
            return(this);
        }
示例#10
0
        public static void UnpackCollectionTo <T>(Unpacker unpacker, MessagePackSerializer <T> serializer, IEnumerable <T> collection, Action <T> addition)
        {
            if (unpacker == null)
            {
                throw new ArgumentNullException("unpacker");
            }

            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }


            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }


            if (addition == null)
            {
                throw new ArgumentNullException("addition");
            }

            if (!unpacker.IsArrayHeader)
            {
                throw SerializationExceptions.NewIsNotArrayHeader();
            }

#if !UNITY
            Contract.EndContractBlock();
#endif // !UNITY

            int count = GetItemsCount(unpacker);
            for (int i = 0; i < count; i++)
            {
                if (!unpacker.Read())
                {
                    throw SerializationExceptions.NewMissingItem(i);
                }

                T item;
                if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
                {
                    item = serializer.UnpackFrom(unpacker);
                }
                else
                {
                    using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
                    {
                        item = serializer.UnpackFrom(subtreeUnpacker);
                    }
                }

                addition(item);
            }
        }
示例#11
0
        public static void UnpackCollectionTo <TDiscarded>(Unpacker unpacker, IEnumerable collection, Func <object, TDiscarded> addition)
        {
            if (unpacker == null)
            {
                SerializationExceptions.ThrowArgumentNullException("unpacker");
            }

            if (collection == null)
            {
                SerializationExceptions.ThrowArgumentNullException("collection");
            }

            if (addition == null)
            {
                SerializationExceptions.ThrowArgumentNullException("addition");
            }

#if ASSERT
            Contract.Assert(unpacker != null);
            Contract.Assert(collection != null);
            Contract.Assert(addition != null);
#endif // ASSERT

            if (!unpacker.IsArrayHeader)
            {
                SerializationExceptions.ThrowIsNotArrayHeader(unpacker);
            }

#if ASSERT
            Contract.EndContractBlock();
#endif // ASSERT

            int count = GetItemsCount(unpacker);
            for (int i = 0; i < count; i++)
            {
                if (!unpacker.Read())
                {
                    SerializationExceptions.ThrowMissingItem(i, unpacker);
                }

                MessagePackObject item;
                if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
                {
                    item = _messagePackObjectSerializer.UnpackFrom(unpacker);
                }
                else
                {
                    using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
                    {
                        item = _messagePackObjectSerializer.UnpackFrom(subtreeUnpacker);
                    }
                }

                addition(item);
            }
        }
示例#12
0
        public static void UnpackArrayTo <T>(Unpacker unpacker, MessagePackSerializer <T> serializer, T[] array)
        {
            if (unpacker == null)
            {
                SerializationExceptions.ThrowArgumentNullException("unpacker");
            }

            if (serializer == null)
            {
                SerializationExceptions.ThrowArgumentNullException("serializer");
            }

            if (array == null)
            {
                SerializationExceptions.ThrowArgumentNullException("array");
            }

#if ASSERT
            Contract.Assert(unpacker != null);
            Contract.Assert(serializer != null);
            Contract.Assert(array != null);
#endif // ASSERT

            if (!unpacker.IsArrayHeader)
            {
                SerializationExceptions.ThrowIsNotArrayHeader(unpacker);
            }

#if ASSERT
            Contract.EndContractBlock();
#endif // ASSERT

            int count = GetItemsCount(unpacker);
            for (int i = 0; i < count; i++)
            {
                if (!unpacker.Read())
                {
                    SerializationExceptions.ThrowMissingItem(i, unpacker);
                }

                T item;
                if (!unpacker.IsArrayHeader && !unpacker.IsMapHeader)
                {
                    item = serializer.UnpackFrom(unpacker);
                }
                else
                {
                    using (Unpacker subtreeUnpacker = unpacker.ReadSubtree())
                    {
                        item = serializer.UnpackFrom(subtreeUnpacker);
                    }
                }

                array[i] = item;
            }
        }
示例#13
0
        ///	<summary>
        ///		Unpacks raw value from the specified <see cref="Stream"/> as <see cref="UnpackingStream"/>.
        ///	</summary>
        ///	<param name="source">The <see cref="Stream"/> which contains Message Pack binary stream.</param>
        ///	<returns>
        ///		The <see cref="UnpackingStream"/> which represents raw value stream.
        ///	</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="source"/> 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.
        ///		Note that the state of <paramref name="source"/> will be unpredictable espicially it is not seekable.
        ///	</exception>
        /// <remarks>
        ///		<para>
        ///			<see cref="UnpackingStream"/> does not own <paramref name="source"/>, so <paramref name="source"/> still should be closed.
        ///		</para>
        ///		<para>
        ///			When the type of packed value is not known, use <see cref="UnpackObject(Stream)"/> instead.
        ///		</para>
        ///	</remarks>
        public static UnpackingStream UnpackByteStream(Stream source)
        {
            ValidateStream(source);
#if !UNITY
            Contract.EndContractBlock();
#endif // !UNITY


            return(UnpackByteStreamCore(source));
        }
示例#14
0
        /// <summary>
        ///		Encode specified string by default encoding.
        /// </summary>
        /// <param name="value">String value.</param>
        /// <returns>Encoded <paramref name="value"/>.</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="value"/> is null.
        /// </exception>
        public static byte[] EncodeString(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            Contract.EndContractBlock();

            return(_utf8NonBom.GetBytes(value));
        }
示例#15
0
        /// <summary>
        ///		Decode specified byte[] by default encoding.
        /// </summary>
        /// <param name="value">Byte[] value.</param>
        /// <returns>Decoded <paramref name="value"/>.</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="value"/> is null.
        /// </exception>
        /// <exception cref="System.Text.DecoderFallbackException">
        ///		<paramref name="value"/> contains non-UTF-8 bits.
        /// </exception>
        public static string DecodeStringStrict(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            Contract.EndContractBlock();

            return(_utf8NonBomStrict.GetString(value, 0, value.Length));
        }
示例#16
0
            /// <summary>
            ///		Copies the entire collection to a compatible one-dimensional array, starting at the beginning of the target array.
            /// </summary>
            /// <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>
            public void CopyTo(MessagePackObject[] array)
            {
                if (array == null)
                {
                    throw new ArgumentNullException("array");
                }

                Contract.EndContractBlock();

                CollectionOperation.CopyTo(this, this.Count, 0, array, 0, this.Count);
            }
        void ICollection <KeyValuePair <MessagePackObject, MessagePackObject> > .Add(KeyValuePair <MessagePackObject, MessagePackObject> item)
        {
            if (item.Key.IsNil)
            {
                ThrowKeyNotNilException("key");
            }

            this.VerifyIsNotFrozen();

            Contract.EndContractBlock();

            this.AddCore(item.Key, item.Value, false);
        }
        /// <summary>
        /// Removes the element with the specified key from the <see cref="MessagePackObjectDictionary"/>.
        /// </summary>
        /// <param name="key">The key of the element to remove.</param>
        /// <returns>
        ///		<c>true</c> if the element is successfully removed; otherwise, <c>false</c>.
        ///		This method also returns false if <paramref name="key"/> was not found in the original <see cref="MessagePackObjectDictionary"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
        /// </exception>
        /// <remarks>
        ///		This method approaches an O(1) operation.
        /// </remarks>
        public bool Remove(MessagePackObject key)
        {
            if (key.IsNil)
            {
                ThrowKeyNotNilException("key");
            }

            this.VerifyIsNotFrozen();

            Contract.EndContractBlock();

            return(this.RemoveCore(key, default(MessagePackObject), false));
        }
        /// <summary>
        ///		Adds the specified key and value to the dictionary.
        /// </summary>
        /// <param name="key">
        ///		The key of the element to add.
        /// </param>
        /// <param name="value">
        ///		The value of the element to add. The value can be <c>null</c> for reference types.
        /// </param>
        /// <returns>
        ///		An element with the same key already does not exist in the dictionary and sucess to add then newly added node;
        ///		otherwise <c>null</c>.
        /// </returns>
        /// <exception cref="ArgumentException">
        ///		<paramref name="key"/> already exists in this dictionary.
        ///		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"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
        /// </exception>
        /// <remarks>
        ///		If <see cref="Count"/> is less than the capacity, this method approaches an O(1) operation.
        ///		If the capacity must be increased to accommodate the new element,
        ///		this method becomes an O(<em>N</em>) operation, where <em>N</em> is <see cref="Count"/>.
        /// </remarks>
        public void Add(MessagePackObject key, MessagePackObject value)
        {
            if (key.IsNil)
            {
                ThrowKeyNotNilException("key");
            }

            this.VerifyIsNotFrozen();

            Contract.EndContractBlock();

            this.AddCore(key, value, false);
        }
        bool ICollection <KeyValuePair <MessagePackObject, MessagePackObject> > .Remove(KeyValuePair <MessagePackObject, MessagePackObject> item)
        {
            if (item.Key.IsNil)
            {
                ThrowKeyNotNilException("key");
            }

            this.VerifyIsNotFrozen();

            Contract.EndContractBlock();

            return(this.RemoveCore(item.Key, item.Value, true));
        }
示例#21
0
        object IDictionary.this[object key]
        {
            get
            {
                if (key == null)
                {
                    throw new ArgumentNullException("key");
                }

#if !UNITY
                Contract.EndContractBlock();
#endif // !UNITY


                var typedKey = ValidateObjectArgument(key, "key");
                if (typedKey.IsNil)
                {
                    ThrowKeyNotNilException("key");
                }

                MessagePackObject value;
                if (!this.TryGetValue(typedKey, out value))
                {
                    return(null);
                }

                return(value);
            }
            set
            {
                if (key == null)
                {
                    throw new ArgumentNullException("key");
                }

                this.VerifyIsNotFrozen();

#if !UNITY
                Contract.EndContractBlock();
#endif // !UNITY


                var typedKey = ValidateObjectArgument(key, "key");
                if (typedKey.IsNil)
                {
                    ThrowKeyNotNilException("key");
                }

                this[typedKey] = ValidateObjectArgument(value, "value");
            }
        }
示例#22
0
        /// <summary>
        ///		Unpacks specified type value with the default context.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="source">The <see cref="Unpacker"/>.</param>
        /// <returns>The deserialized value.</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="source"/> 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)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

#if !UNITY
            Contract.EndContractBlock();
#endif // !UNITY


            return(UnpackCore <T>(source, new SerializationContext()));
        }
示例#23
0
        protected virtual void WriteBytes(byte[] value, bool isImmutable)
        {
            if (value == null)
            {
                ThrowArgumentNullException("value");
            }

            Contract.EndContractBlock();

            // ReSharper disable once PossibleNullReferenceException
            foreach (var b in value)
            {
                this.WriteByte(b);
            }
        }
示例#24
0
        ///	<summary>
        ///		Unpacks raw value from the specified <see cref="Stream"/> as <see cref="UnpackingStreamReader"/> 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 <see cref="UnpackingStreamReader"/> which represents raw value stream as UTF-8 string.
        ///	</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.
        ///		Note that the state of <paramref name="source"/> will be unpredictable espicially it is not seekable.
        ///	</exception>
        /// <remarks>
        ///		<para>
        ///			if <paramref name="source"/> contains invalid sequence as specified encoding string,
        ///			the <see cref="DecoderFallbackException"/> may occurs on read char.
        ///		</para>
        ///		<para>
        ///			<see cref="UnpackingStreamReader"/> does not own <paramref name="source"/>, so <paramref name="source"/> still should be closed.
        ///		</para>
        ///		<para>
        ///			When the type of packed value is not known, use <see cref="UnpackObject(Stream)"/> instead.
        ///		</para>
        ///	</remarks>
        public static UnpackingStreamReader UnpackCharStream(Stream source, Encoding encoding)
        {
            ValidateStream(source);

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            Contract.EndContractBlock();

            var stream = UnpackByteStreamCore(source);

            return(new DefaultUnpackingStreamReader(stream, encoding, stream.RawLength));
        }
        /// <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");
            }

            Contract.EndContractBlock();
            this.AssertInvariant();

            return
                (this._dictionary == null
                                ? this._keys.Contains(key, MessagePackObjectEqualityComparer.Instance)
                                : this._dictionary.ContainsKey(key));
        }
示例#26
0
        /// <summary>
        ///		Packs specified value with the default 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>
        /// <returns><paramref name="source"/>.</returns>
        /// <exception cref="ArgumentNullException">
        ///		<paramref name="source"/> 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)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

#if !UNITY
            Contract.EndContractBlock();
#endif // !UNITY


            PackCore(source, value, SerializationContext.Default);
            return(source);
        }
示例#27
0
        /// <summary>
        ///		Writes specified bytes to stream using implementation specific most efficient manner asynchronously.
        /// </summary>
        /// <param name="value">Bytes to be written.</param>
        /// <param name="isImmutable">If the <paramref name="value"/> can be treat as immutable (that is, can be used safely without copying) then <c>true</c>.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
        protected virtual async Task WriteBytesAsync(byte[] value, bool isImmutable, CancellationToken cancellationToken)
        {
            if (value == null)
            {
                ThrowArgumentNullException("value");
            }

            Contract.EndContractBlock();

            // ReSharper disable once PossibleNullReferenceException
            foreach (var b in value)
            {
                await this.WriteByteAsync(b, cancellationToken).ConfigureAwait(false);
            }
        }
示例#28
0
        ///	<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);
            }
        }
示例#29
0
        ///	<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>
        /// 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);
            }
        }