aboutsummaryrefslogtreecommitdiff
path: root/cs-dotnet/src/gatsstring.cs
blob: 0935b05d60c4567f211a97637c04801a4bd76c64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * 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
{
    /// <summary>
    /// Encapsulates a single byte array.
    /// </summary>
    /// <remarks>
    /// A GATS string, unlike a C# string primitive, is simply an array of
    /// bytes.  This is actually more flexible in many ways, as it allows a
    /// GatsString to contain any binary data.  However, to encode textual data
    /// there is no hard and fast standard.  If a string primitive is passed
    /// into a GatsString it will be encoded into UTF-8.  If you would rather
    /// use a different encoding then encode your data first, and then pass it
    /// in as a byte array.
    ///
    /// The ToString implementation provided by GatsString also assumes that
    /// the contained data is UTF-8 encoded.  This may cause some minor issues
    /// when attempting to debug strings that contain binary.
    /// </remarks>
    public class GatsString : GatsObject
    {
        public byte[] Value { get; set; }

        public GatsString()
        {
        }

        public GatsString( byte[] val )
        {
            Value = val;
        }

        public GatsString( string val )
        {
            Value = System.Text.Encoding.UTF8.GetBytes( val );
        }

        public override string ToString()
        {
            return System.Text.Encoding.UTF8.GetString( Value );
        }

        public override void Read( Stream s, char cType )
        {
            int Size = (int)GatsInteger.ReadPackedInt( s );
            Value = new byte[Size];
            int SoFar = 0;
            do
            {
                SoFar += s.Read( Value, SoFar, Size-SoFar );
            } while( SoFar < Size );
        }

        public override void Write( Stream s )
        {
            s.WriteByte( (byte)'s' );
            if( Value == null )
            {
                GatsInteger.WritePackedInt( s, 0 );
            }
            else
            {
                GatsInteger.WritePackedInt( s, Value.Length );
                s.Write( Value, 0, Value.Length );
            }
        }
    };
}