aboutsummaryrefslogtreecommitdiff
path: root/java/com/xagasoft/gats/GatsInputStream.java
blob: 5cd830dcfedef282890812d48aea7979a04c5369 (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
package com.xagasoft.gats;

import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

public class GatsInputStream
{
	private InputStream is;
	private ByteArrayOutputStream baos = new ByteArrayOutputStream();
	private int iVer = 0;
	private int iSize;

	public GatsInputStream( InputStream is )
	{
		this.is = is;
	}

	public GatsObject readObject() throws java.io.IOException
	{
		do
		{
			iVer = is.read();
		} while( iVer == 0 );

		switch( iVer )
		{
			case 1:
				DataInputStream dis = new DataInputStream( is );
				iSize = dis.readInt();
				return GatsObject.read( is );
		}

		return null;
	}

		/*
	public GatsObject readObject() throws java.io.IOException
	{
		do
		{
			if( baos.size() < 5 )
			{
				byte aBuf[] = new byte[5-baos.size()];
				int iRead = is.read( aBuf );
				baos.write( aBuf, 0, iRead );

				if( baos.size() < 5 )
					return null;
			}
		} while( !skipReadNulls() );

		if( iVer == 0 )
		{
			ByteArrayInputStream bais = new ByteArrayInputStream(
				baos.toByteArray()
				);
			DataInputStream dis = new DataInputStream( bais );
			iVer = dis.readUnsignedByte();
			iSize = dis.readInt();
		}

		byte aBuf[] = new byte[1500];
		while( baos.size() < iSize )
		{
			int iGoal = iSize-baos.size();
			if( iGoal > 1500 )
				iGoal = 1500;

			int iRead = is.read( aBuf, 0, iGoal );
			baos.write( aBuf, 0, iRead );

			if( iRead < iGoal )
				return null;
		}

		if( baos.size() < iSize )
			return null;

		byte aTmp[] = baos.toByteArray();
		ByteArrayInputStream bais = new ByteArrayInputStream(
			aTmp
			);
		bais.skip( 5 );
		
		GatsObject goRet = GatsObject.read( bais );

		baos.reset();
		baos.write( aTmp, iSize, aTmp.length-iSize );
		
		iVer = 0;

		return goRet;
	}

	private boolean skipReadNulls()
	{
		if( baos.size() == 0 )
			return false;

		byte aBuf[] = baos.toByteArray();
		if( aBuf[0] != 0 )
			return true;

		for( int j = 1; j < aBuf.length; j++ )
		{
			if( aBuf[j] != 0 )
			{
				baos.reset();
				baos.write( aBuf, j, aBuf.length-j );
				return true;
			}
		}

		baos.reset();
		return true;
	}
	*/
};