aboutsummaryrefslogtreecommitdiff
path: root/java/com/xagasoft/gats/GatsInteger.java
blob: b6b8208a7a6cf102855d59201061522cb2623b2c (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
 * Copyright (C) 2007-2013 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.
 */

package com.xagasoft.gats;

import java.io.OutputStream;
import java.io.InputStream;

/**
 * Represents a simple java long value.  This does not handle arbitrary
 * precision integer values, a class to handle that is forthcoming.
 */
public class GatsInteger extends GatsObject
{
	private long iValue = 0;

	public GatsInteger()
	{
	}

	public GatsInteger( long iValue )
	{
		this.iValue = iValue;
	}

	public long getValue()
	{
		return iValue;
	}

	public void setValue( long iValue )
	{
		this.iValue = iValue;
	}

	public String toString()
	{
		return "" + iValue;
	}

	public int getType()
	{
		return GatsObject.INTEGER;
	};

	void read( InputStream is, char cType ) throws java.io.IOException

	{
		iValue = readPackedInt( is );
	}

	void write( OutputStream os ) throws java.io.IOException
	{
		os.write( (int)'i' );
		writePackedInt( os, iValue );
	}

	/**
	 * This is a general helper function used by several parts of the Gats
	 * system.
	 * It reads a "packed integer" from the given input stream, and returns the
	 * value.
	 * Possible TODO: have this return a Number, and construct either a Long
	 * or BigInteger when appropriate.
	 */
	public static long readPackedInt( InputStream is ) throws java.io.IOException
	{
		int b;
		long rOut = 0;
		boolean bNeg;
		
		b = is.read();
		bNeg = (b&0x40) == 0x40;
		rOut |= b&0x3F;
		int c = 0;
		while( (b&0x80) == 0x80 )
		{
			b = is.read();
			rOut |= (long)(b&0x7F) << (6+7*(c++));
		}
		if( bNeg )
			return -rOut;
		return rOut;
	}

	/**
	 * This is a general helper function used by several parts of the Gats
	 * system.
	 * It writes a "packed integer" to the given output stream.
	 */
	public static void writePackedInt( OutputStream os, long iIn ) throws java.io.IOException
	{
		int b;

		if( iIn < 0 )
		{
			iIn = -iIn;
			b = (int)(iIn&0x3F);
			if( iIn > b )
				b |= 0x80 | 0x40;
			else
				b |= 0x40;
		}
		else
		{
			b = (int)(iIn&0x3F);
			if( iIn > b )
				b |= 0x80;
		}
		os.write( b );
		iIn = iIn >> 6;

		while( iIn > 0 )
		{
			b = (int)(iIn&0x7F);
			if( iIn > b )
				b |= 0x80;
			os.write( b );
			iIn = iIn >> 7;
		}
	}
};