diff options
Diffstat (limited to '')
-rw-r--r-- | cs-dotnet/src/gatsinteger.cs | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/cs-dotnet/src/gatsinteger.cs b/cs-dotnet/src/gatsinteger.cs new file mode 100644 index 0000000..cbb552e --- /dev/null +++ b/cs-dotnet/src/gatsinteger.cs | |||
@@ -0,0 +1,86 @@ | |||
1 | using System.IO; | ||
2 | |||
3 | namespace Com.Xagasoft.Gats | ||
4 | { | ||
5 | public class GatsInteger : GatsObject | ||
6 | { | ||
7 | public long Value { get; set; } | ||
8 | |||
9 | public GatsInteger( long val=0 ) | ||
10 | { | ||
11 | Value = val; | ||
12 | } | ||
13 | |||
14 | public override string ToString() | ||
15 | { | ||
16 | return Value.ToString(); | ||
17 | } | ||
18 | |||
19 | public override void Read( Stream s, byte cType ) | ||
20 | { | ||
21 | Value = ReadPackedInt( s ); | ||
22 | } | ||
23 | |||
24 | public override void Write( Stream s ) | ||
25 | { | ||
26 | s.WriteByte( (int)'i' ); | ||
27 | WritePackedInt( s, Value ); | ||
28 | } | ||
29 | |||
30 | public static long ReadPackedInt( Stream s ) | ||
31 | { | ||
32 | int b; | ||
33 | long rOut = 0; | ||
34 | bool bNeg; | ||
35 | |||
36 | b = s.ReadByte(); | ||
37 | if( b == -1 ) | ||
38 | throw new GatsException("Premature end of stream encountered."); | ||
39 | bNeg = (b&0x40) == 0x40; | ||
40 | rOut |= ((long)b)&0x3F; | ||
41 | int c = 0; | ||
42 | while( (b&0x80) == 0x80 ) | ||
43 | { | ||
44 | b = s.ReadByte(); | ||
45 | if( b == -1 ) | ||
46 | throw new GatsException("Premature end of stream encountered."); | ||
47 | rOut |= (long)(b&0x7F) << (6+7*(c++)); | ||
48 | } | ||
49 | if( bNeg ) | ||
50 | return -rOut; | ||
51 | return rOut; | ||
52 | } | ||
53 | |||
54 | public static void WritePackedInt( Stream s, long iIn ) | ||
55 | { | ||
56 | byte b; | ||
57 | |||
58 | if( iIn < 0 ) | ||
59 | { | ||
60 | iIn = -iIn; | ||
61 | b = (byte)(iIn&0x3F); | ||
62 | if( iIn > b ) | ||
63 | b |= 0x80 | 0x40; | ||
64 | else | ||
65 | b |= 0x40; | ||
66 | } | ||
67 | else | ||
68 | { | ||
69 | b = (byte)(iIn&0x3F); | ||
70 | if( iIn > b ) | ||
71 | b |= 0x80; | ||
72 | } | ||
73 | s.WriteByte( b ); | ||
74 | iIn = iIn >> 6; | ||
75 | |||
76 | while( iIn > 0 ) | ||
77 | { | ||
78 | b = (byte)(iIn&0x7F); | ||
79 | if( iIn > b ) | ||
80 | b |= 0x80; | ||
81 | s.WriteByte( b ); | ||
82 | iIn = iIn >> 7; | ||
83 | } | ||
84 | } | ||
85 | }; | ||
86 | } | ||