/*
* Copyright (C) 2007-2012 Xagasoft, All rights reserved.
*
* This file is part of the libgats library and is released under the
* terms of the license contained in the file LICENSE.
*/
using System.IO;
namespace Com.Xagasoft.Gats
{
///
/// The base class of all GATS Data Type classes.
///
///
/// This provides the standard Read and Write methods that are used to do
/// all type serialization, as well as a handy static Read function that
/// can be used
/// to read in any type. These methods should not be used in normal
/// programming, instead use the GatsStream class to read and write
/// complete GATS packets.
///
public abstract class GatsObject
{
///
/// Read a single object from the provided stream.
///
///
/// This method does not read the leading type character. The static
/// Read method in GatsObject does this, and passes the type into the
/// Read method as a parameter in case it's needed by a specific type,
/// such as GatsBoolean.
///
/// The Stream derived class to read from.
/// The already read type specifier.
public abstract void Read( Stream s, char type );
///
/// Write a single object to the provided stream.
///
///
/// Unlike the Read method, this does actually write the leading type
/// specifier.
///
/// The Stream derived class to write to.
public abstract void Write( Stream s );
///
/// Reads a GatsObject from the provided stream and returns it.
///
///
/// This method reads the initial type specifier byte, constructs the
/// proper object, calls the Read method on that object, and returns
/// the result.
///
///
/// The constructed object, or null if an end type was found.
///
public static GatsObject Read( Stream s )
{
int b = s.ReadByte();
if( b == -1 )
throw new GatsException( GatsException.Type.PrematureEnd );
char type = (char)b;
GatsObject ret = null;
switch( type )
{
case 'i':
ret = new GatsInteger();
break;
case 's':
ret = new GatsString();
break;
case '0':
case '1':
ret = new GatsBoolean();
break;
case 'l':
ret = new GatsList();
break;
case 'd':
ret = new GatsDictionary();
break;
case 'f':
case 'F':
ret = new GatsFloat();
break;
case 'n':
ret = new GatsNull();
break;
case 'e':
return null;
default:
throw new GatsException( GatsException.Type.InvalidType );
}
ret.Read( s, type );
return ret;
}
}
}