/// <summary>
        /// Defines the deserialization for the Datetime.
        /// </summary>
        /// <returns>The from core.</returns>
        /// <param name="unpacker">Unpacker.</param>
        protected override DateTime UnpackFromCore(Unpacker unpacker)
        {
            DateTime                      epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            MessagePackObject             obj   = unpacker.LastReadData;
            MessagePackExtendedTypeObject ext   = obj.AsMessagePackExtendedTypeObject();

            byte[] bytes = ext.GetBody();
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }
            double val;

            if (bytes.Length == 1)
            {
                val = Convert.ToDouble(bytes[0]);
            }
            else if (bytes.Length == 2)
            {
                val = Convert.ToDouble(BitConverter.ToInt16(bytes, 0));
            }
            else if (bytes.Length == 4)
            {
                val = Convert.ToDouble(BitConverter.ToInt32(bytes, 0));
            }
            else
            {
                val = Convert.ToDouble(BitConverter.ToInt64(bytes, 0));
            }
            return(epoch.AddMilliseconds(val));
        }
		public void TestProperties()
		{
			byte typeCode = 0;
			var body = new byte[] { 1 };
			var actual = new MessagePackExtendedTypeObject( typeCode, body );

			Assert.That( actual.TypeCode, Is.EqualTo( typeCode ) );
			Assert.That( actual.Body, Is.SameAs( body ) );
			Assert.That( actual.GetBody(), Is.Not.SameAs( body ).And.EqualTo( body ) );
		}
            protected void ReadPrimitive()
            {
                MessagePackObject lastReadData = mUnpacker.LastReadData;

                if (lastReadData.IsNil)
                {
                    mReader.SetToken(JsonToken.Null, null);
                }
                else if (lastReadData.UnderlyingType == typeof(byte[]))
                {
                    mReader.SetToken(JsonToken.Bytes, lastReadData.AsBinary());
                }
                else if (lastReadData.UnderlyingType == typeof(bool))
                {
                    mReader.SetToken(JsonToken.Boolean, lastReadData.AsBoolean());
                }
                else if (lastReadData.UnderlyingType == typeof(string))
                {
                    mReader.SetToken(JsonToken.String, lastReadData.AsString());
                }
                else if (lastReadData.UnderlyingType == typeof(double) ||
                         lastReadData.UnderlyingType == typeof(float))
                {
                    mReader.SetToken(JsonToken.Float, lastReadData.ToObject());
                }
                else if (lastReadData.UnderlyingType == typeof(MessagePackExtendedTypeObject))
                {
                    MessagePackExtendedTypeObject extendedTypeObject =
                        lastReadData.AsMessagePackExtendedTypeObject();

                    if (extendedTypeObject.TypeCode == KnownExtTypeCode.Timestamp)
                    {
                        mReader.SetToken(JsonToken.Date, lastReadData.AsTimestamp().ToDateTime());
                    }
                }
                else if (lastReadData.IsTypeOf <sbyte>() == true ||
                         lastReadData.IsTypeOf <short>() == true ||
                         lastReadData.IsTypeOf <ushort>() == true ||
                         lastReadData.IsTypeOf <int>() == true ||
                         lastReadData.IsTypeOf <uint>() == true ||
                         lastReadData.IsTypeOf <long>() == true ||
                         lastReadData.IsTypeOf <ulong>() == true)
                {
                    mReader.SetToken(JsonToken.Integer, lastReadData.ToObject());
                }
            }
		public void TestEquality_ValueEqual()
		{
			foreach ( var testCase in
				new[]
				{
					Tuple.Create( 0, 0, new byte[] {1}, new byte[] {1}, true ),
					Tuple.Create( 0, 1, new byte[] {1}, new byte[] {1}, false ),
					Tuple.Create( 0, 0, new byte[] {1}, new byte[] {1, 2}, false ),
					Tuple.Create( 0, 0, new byte[] {1}, new byte[] {2}, false ),
				} )
			{
				checked
				{
					var left = new MessagePackExtendedTypeObject( ( byte )testCase.Item1, testCase.Item3 );
					var right = new MessagePackExtendedTypeObject( ( byte )testCase.Item2, testCase.Item4 );

					Assert.That( left.Equals( right ), Is.EqualTo( testCase.Item5 ), "IEquatable.Equals" );
					Assert.That( left.Equals( ( object )right ), Is.EqualTo( testCase.Item5 ), "Equals" );
					Assert.That( left == right, Is.EqualTo( testCase.Item5 ), "==" );
					Assert.That( left != right, Is.EqualTo( !testCase.Item5 ), "!=" );
				}
			}
		}
		public void TestToString_ExtendedTypeObject_AsIs()
		{
			var mpeto = new MessagePackExtendedTypeObject( 123, new byte[] {1, 2, 3} );
			Assert.AreEqual(
				mpeto.ToString(),
				new MessagePackObject( mpeto ).ToString()
			);
		}
Example #6
0
		public void TestExts()
		{
			var sw = new Stopwatch();
			foreach (
				var count in
				new[]
				{
					0, // empty
					1, // fixext1
					2, // fixext2
					4, // fixext4
					8, // fixext8
					16, // fixext16
					17, // min ext8 size
					0xff, // max ext8 size
					0x100, // min ext16 size
					0xffff, // max ext16 size
					0x10000, // min ext32 size
				}
			)
			{
				sw.Restart();
				var output = new MemoryStream();
				var value = new MessagePackExtendedTypeObject(
					1, Enumerable.Range( 0, count ).Select( i => ( byte ) ( i % 0x100 ) ).ToArray() );
				Packer.Create( output, PackerCompatibilityOptions.None ).Pack( value );
				Assert.AreEqual(
					value,
					UnpackOne( output ).AsMessagePackExtendedTypeObject()
				);
				sw.Stop();
			}

			Console.WriteLine( "Ext: {0:0.###} msec/byte", sw.Elapsed.TotalMilliseconds / 0x10000 );
		}
		/// <summary>
		///		Reads next nullable <see cref="MessagePackExtendedTypeObject" /> value from current stream.
		///	</summary>
		/// <returns>
		///		The nullable <see cref="MessagePackExtendedTypeObject" /> value read from current data source successfully.
		/// </returns>
		/// <exception cref="InvalidMessagePackStreamException">
		///		Cannot read a value because the underlying stream unexpectedly ends.
		/// </exception>
		/// <exception cref="MessageTypeException">
		///		A value read from data source is not compatible for the nullable <see cref="MessagePackExtendedTypeObject" /> type.
		/// </exception>
		public virtual bool ReadNullableMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject? result )
		{
			if( !this.Read() )
			{
				result = null;
				return false;
			}

			result = this.LastReadData.IsNil ? default( MessagePackExtendedTypeObject? ) : this.LastReadData.AsMessagePackExtendedTypeObject();
			return true;
		}
		/// <summary>
		///		Reads next <see cref="MessagePackExtendedTypeObject" /> value from current stream.
		///	</summary>
		/// <param name="result">
		///		The <see cref="MessagePackExtendedTypeObject" /> value read from current stream to be stored when operation is succeeded.
		/// </param>
		/// <returns>
		///		<c>true</c> if expected value was read from stream; <c>false</c> if no more data on the stream.
		///		Note that this method throws exception for unexpected state. See exceptions section.
		/// </returns>
		/// <exception cref="InvalidMessagePackStreamException">
		///		Cannot read a value because the underlying stream unexpectedly ends.
		/// </exception>
		/// <exception cref="MessageTypeException">
		///		A value read from data source is not compatible for the <see cref="MessagePackExtendedTypeObject" /> type.
		/// </exception>
		public virtual bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result )
		{
			if( !this.Read() )
			{
				result = default( MessagePackExtendedTypeObject );
				return false;
			}

			result = this.LastReadData.AsMessagePackExtendedTypeObject();
			return true;
		}
		public override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result )
		{
			this.DiscardCompletedStacks();
			
			if ( this._itemsCount.Count == 0 )
			{
				result = default( MessagePackExtendedTypeObject );
				return false;
			}
			
			if ( !this._root.ReadSubtreeMessagePackExtendedTypeObject( out result ) )
			{
				return false;
			}
			
			switch ( this._root.InternalCollectionType )
			{
				case ItemsUnpacker.CollectionType.Array:
				{
					this._itemsCount.Push( this._root.InternalItemsCount );
					this._unpacked.Push( 0 );
					this._isMap.Push( false );
					break;
				}
				case ItemsUnpacker.CollectionType.Map:
				{
					this._itemsCount.Push( this._root.InternalItemsCount * 2 );
					this._unpacked.Push( 0 );
					this._isMap.Push( true );
					break;
				}
				default:
				{
					this._unpacked.Push( this._unpacked.Pop() + 1 );
					break;
				}
			}
			
			return true;
		}
Example #10
0
		internal bool ReadSubtreeMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result )
		{
			byte header;
			long integral;
			float real32;
			double real64;
			var type = this.ReadValue( out header, out integral, out real32, out real64 );
			switch( type )
			{
				case ReadValueResult.Eof:
				{
					result = default( MessagePackExtendedTypeObject );
					return false;
				}
				case ReadValueResult.FixExt1:
				case ReadValueResult.FixExt2:
				case ReadValueResult.FixExt4:
				case ReadValueResult.FixExt8:
				case ReadValueResult.FixExt16:
				case ReadValueResult.Ext8:
				case ReadValueResult.Ext16:
				case ReadValueResult.Ext32:
				{
					result = this.ReadMessagePackExtendedTypeObjectCore( type );
					return true;
				}
				default:
				{
					this.ThrowTypeException( typeof( MessagePackExtendedTypeObject ), header );
					// Never reach
					result = default( MessagePackExtendedTypeObject );
					return false;
				}
			}
		} 
Example #11
0
		public override bool ReadMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result )
		{
			this.EnsureNotInSubtreeMode();
			return this.ReadSubtreeMessagePackExtendedTypeObject( out result );
		} 
		internal bool ReadSubtreeMessagePackExtendedTypeObject( out MessagePackExtendedTypeObject result )
		{
			var source = this._stream;
		#pragma warning disable 168
			var buffer = this._scalarBuffer;
		#pragma warning restore 168
			#region UnpackExt
			#if DEBUG && !UNITY_ANDROID && !UNITY_IPHONE
			Contract.Assert( source != null );
			Contract.Assert( buffer != null );
			#endif // DEBUG && !UNITY_ANDROID && !UNITY_IPHONE
			
			var header = source.ReadByte();
			if( header < 0 )
			{
				throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
			}
			
			switch( header )
			{
				case MessagePackCode.FixExt1:
				{
					#region UnpackExt
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ 1 ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.FixExt2:
				{
					#region UnpackExt
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ 2 ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.FixExt4:
				{
					#region UnpackExt
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ 4 ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.FixExt8:
				{
					#region UnpackExt
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ 8 ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.FixExt16:
				{
					#region UnpackExt
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ 16 ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.Ext8:
				{
					#region UnpackExt
			
					Byte length;
					#region UnpackScalar
					
					var read = source.Read( buffer, 0, 1 );
					if( read == 1 )
					{
						length = BigEndianBinary.ToByte( buffer, 0 );
					}
					else
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackScalar
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ length ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.Ext16:
				{
					#region UnpackExt
			
					UInt16 length;
					#region UnpackScalar
					
					var read = source.Read( buffer, 0, 2 );
					if( read == 2 )
					{
						length = BigEndianBinary.ToUInt16( buffer, 0 );
					}
					else
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackScalar
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ length ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				case MessagePackCode.Ext32:
				{
					#region UnpackExt
			
					UInt32 length;
					#region UnpackScalar
					
					var read = source.Read( buffer, 0, 4 );
					if( read == 4 )
					{
						length = BigEndianBinary.ToUInt32( buffer, 0 );
					}
					else
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackScalar
			
					if( length > Int32.MaxValue )
					{
						throw new MessageNotSupportedException( "MessagePack for CLI cannot handle large binary which has more than Int32.MaxValue bytes." );
					}
			
					var typeCode = source.ReadByte();
					if( typeCode < 0 )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
			
					var data = new byte[ length ];
					#region UnpackRawContent
					
					var bytesRead = source.Read( data, 0, data.Length );
					if( bytesRead < data.Length )
					{
						throw new InvalidMessagePackStreamException( "Stream unexpectedly ends." );
					}
					
					#endregion UnpackRawContent
					var resultMpoValue = MessagePackExtendedTypeObject.Unpack( unchecked( ( byte )typeCode ), data );
					this.InternalCollectionType = CollectionType.None;
					result = resultMpoValue;
					return true;
					#endregion UnpackExt
				}
				default:
				{
					throw new MessageTypeException( String.Format( CultureInfo.CurrentCulture, "Cannot convert '{0}' type value from type '{2}'(0x{1:X}).", "map header", header, MessagePackCode.ToString( header ) ) );
				}
			}// switch
			#endregion UnpackExt
		}
Example #13
0
		public void TestExts_Splitted()
		{
			foreach (
				var count in
					new[]
					{
						0, // empty
						1, // fixext1
						2, // fixext2
						4, // fixext4
						8, // fixext8
						16, // fixext16
						17, // min ext8 size
						0xff, // max ext8 size
						0x100, // min ext16 size
						0xffff, // max ext16 size
						0x10000, // min ext32 size
					}
			)
			{
				using ( var output = new MemoryStream() )
				{
					var value = new MessagePackExtendedTypeObject(
						1, Enumerable.Range( 0, count ).Select( i => ( byte )( i % 0x100 ) ).ToArray() );
					Packer.Create( output, PackerCompatibilityOptions.None ).PackExtendedTypeValue( value );
					output.Position = 0;
					using ( var splitted = new SplittingStream( output ) )
					{
						Assert.AreEqual(
							value,
							Unpacking.UnpackObject( splitted ).AsMessagePackExtendedTypeObject()
						);
					}
				}
			}
		}
		public void TestEquality_Self()
		{
			var left = new MessagePackExtendedTypeObject( 0, new byte[] { 1 } );
			var right = left;

			Assert.That( left.Equals( right ), Is.True, "IEquatable.Equals" );
			Assert.That( left.Equals( ( object )right ), Is.True, "Equals" );
			Assert.That( left == right, Is.True, "==" );
			Assert.That( left != right, Is.False, "!=" );
		}