summaryrefslogtreecommitdiff
path: root/tier2/utlstreambuffer.cpp
blob: 023a6828f66547fd238fa7c378b56042b452bbf2 (plain) (blame)
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//
// Serialization/unserialization buffer
//=============================================================================//


#include "tier2/utlstreambuffer.h"
#include "tier2/tier2.h"
#include "filesystem.h"


//-----------------------------------------------------------------------------
// default stream chunk size
//-----------------------------------------------------------------------------
enum
{
	DEFAULT_STREAM_CHUNK_SIZE = 16 * 1024
};


//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CUtlStreamBuffer::CUtlStreamBuffer( ) : BaseClass( DEFAULT_STREAM_CHUNK_SIZE, DEFAULT_STREAM_CHUNK_SIZE, 0 )
{
	SetUtlBufferOverflowFuncs( &CUtlStreamBuffer::StreamGetOverflow, &CUtlStreamBuffer::StreamPutOverflow );
	m_hFileHandle = FILESYSTEM_INVALID_HANDLE;
	m_pFileName = NULL;
	m_pPath = NULL;
}

CUtlStreamBuffer::CUtlStreamBuffer( const char *pFileName, const char *pPath, int nFlags, bool bDelayOpen ) :
	BaseClass( DEFAULT_STREAM_CHUNK_SIZE, DEFAULT_STREAM_CHUNK_SIZE, nFlags )
{
	SetUtlBufferOverflowFuncs( &CUtlStreamBuffer::StreamGetOverflow, &CUtlStreamBuffer::StreamPutOverflow );

	if ( bDelayOpen )
	{
		m_pFileName = V_strdup( pFileName );

		if ( pPath )
		{
			int nPathLen = Q_strlen( pPath );
			m_pPath = new char[ nPathLen + 1 ];
			Q_strcpy( m_pPath, pPath );
		}
		else
		{
			m_pPath = new char[ 1 ];
			m_pPath[0] = 0;
		}

		m_hFileHandle = FILESYSTEM_INVALID_HANDLE;
	}
	else
	{
		m_pFileName = NULL;
		m_pPath = NULL;
		m_hFileHandle = OpenFile( pFileName, pPath );
		if ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
		{
			return;
		}
	}

	if ( IsReadOnly() )
	{
		// NOTE: MaxPut may not actually be this exact size for text files;
		// it could be slightly less owing to the /r/n -> /n conversion
		m_nMaxPut = g_pFullFileSystem->Size( m_hFileHandle );

		// Read in the first bytes of the file
		if ( Size() > 0 )
		{
			int nSizeToRead = min( Size(), m_nMaxPut );
			ReadBytesFromFile( nSizeToRead, 0 );
		}
	}
}


void CUtlStreamBuffer::Close()
{
	if ( !IsReadOnly() )
	{
		// Write the final bytes
		int nBytesToWrite = TellPut() - m_nOffset;
		if ( nBytesToWrite > 0 )
		{
			if ( ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE ) && m_pFileName )
			{
				m_hFileHandle = OpenFile( m_pFileName, m_pPath );
				if( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
				{
					Error( "CUtlStreamBuffer::Close() Unable to open file %s!\n", m_pFileName );
				}
			}
			if ( m_hFileHandle != FILESYSTEM_INVALID_HANDLE )
			{
				if ( g_pFullFileSystem )
				{
					int nBytesWritten = g_pFullFileSystem->Write( Base(), nBytesToWrite, m_hFileHandle );
					if( nBytesWritten != nBytesToWrite )
					{
						Error( "CUtlStreamBuffer::Close() Write %s failed %d != %d.\n", m_pFileName, nBytesWritten, nBytesToWrite );
					}
				}
			}
		}
	}

	if ( m_hFileHandle != FILESYSTEM_INVALID_HANDLE )
	{
		if ( g_pFullFileSystem )
			g_pFullFileSystem->Close( m_hFileHandle );
		m_hFileHandle = FILESYSTEM_INVALID_HANDLE;
	}

	if ( m_pFileName )
	{
		delete[] m_pFileName;
		m_pFileName = NULL;
	}

	if ( m_pPath )
	{
		delete[] m_pPath;
		m_pPath = NULL;
	}

	m_Error = 0;
}

CUtlStreamBuffer::~CUtlStreamBuffer()
{
	Close();
}


//-----------------------------------------------------------------------------
// Open the file. normally done in constructor
//-----------------------------------------------------------------------------
void CUtlStreamBuffer::Open( const char *pFileName, const char *pPath, int nFlags )
{
	if ( IsOpen() )
	{
		Close();
	}

	m_Get = 0;
	m_Put = 0;
	m_nTab = 0;
	m_nOffset = 0;
	m_Flags = nFlags;
	m_hFileHandle = OpenFile( pFileName, pPath );
	if ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
		return;

	if ( IsReadOnly() )
	{
		// NOTE: MaxPut may not actually be this exact size for text files;
		// it could be slightly less owing to the /r/n -> /n conversion
		m_nMaxPut = g_pFullFileSystem->Size( m_hFileHandle );

		// Read in the first bytes of the file
		if ( Size() > 0 )
		{
			int nSizeToRead = min( Size(), m_nMaxPut );
			ReadBytesFromFile( nSizeToRead, 0 );
		}
	}
	else
	{
		if ( m_Memory.NumAllocated() != 0 )
		{
			m_nMaxPut = -1;
			AddNullTermination();
		}
		else
		{
			m_nMaxPut = 0;
		}
	}
}


//-----------------------------------------------------------------------------
// Is the file open?
//-----------------------------------------------------------------------------
bool CUtlStreamBuffer::IsOpen() const
{
	if ( m_hFileHandle != FILESYSTEM_INVALID_HANDLE )
		return true;

	// Delayed open case
	return ( m_pFileName != 0 );
}


//-----------------------------------------------------------------------------
// Grow allocation size to fit requested size
//-----------------------------------------------------------------------------
void CUtlStreamBuffer::GrowAllocatedSize( int nSize )
{
	int nNewSize = Size();
	if ( nNewSize < nSize + 1 )
	{
		while ( nNewSize < nSize + 1 )
		{
			nNewSize += DEFAULT_STREAM_CHUNK_SIZE; 
		}
		m_Memory.Grow( nNewSize - Size() );
	}
}


//-----------------------------------------------------------------------------
// Load up more of the stream when we overflow
//-----------------------------------------------------------------------------
bool CUtlStreamBuffer::StreamPutOverflow( int nSize )
{
	if ( !IsValid() || IsReadOnly() )
		return false;

	// Make sure the allocated size is at least as big as the requested size
	if ( nSize > 0 )
	{
		GrowAllocatedSize( nSize + 2 );
	}

	// Don't write the last byte (for NULL termination logic to work)
	int nBytesToWrite = TellPut() - m_nOffset - 1;
	if ( ( nBytesToWrite > 0 ) || ( nSize < 0 ) )
	{
		if ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
		{
			m_hFileHandle = OpenFile( m_pFileName, m_pPath );
			if( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
				return false;
		}
	}

	if ( nBytesToWrite > 0 )
	{
		int nBytesWritten = g_pFullFileSystem->Write( Base(), nBytesToWrite, m_hFileHandle );
		if ( nBytesWritten != nBytesToWrite )
		{
			m_Error	|= FILE_WRITE_ERROR;
			return false;
		}

		// This is necessary to deal with auto-NULL terminiation
		m_Memory[0] = *(unsigned char*)PeekPut( -1 );
		if ( TellPut() < Size() )
		{
			m_Memory[1] = *(unsigned char*)PeekPut( );
		}
		m_nOffset = TellPut() - 1;
	}

	if ( nSize < 0 )
	{
		m_nOffset = -nSize-1;
		g_pFullFileSystem->Seek( m_hFileHandle, m_nOffset, FILESYSTEM_SEEK_HEAD );
	}

	return true;
}


//-----------------------------------------------------------------------------
// Reads bytes from the file; fixes up maxput if necessary and null terminates
//-----------------------------------------------------------------------------
int CUtlStreamBuffer::ReadBytesFromFile( int nBytesToRead, int nReadOffset )
{
	if ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
	{
		if ( !m_pFileName )
		{
			Warning( "File has not been opened!\n" );
			Assert(0);
			return 0;
		}

		m_hFileHandle = OpenFile( m_pFileName, m_pPath );
		if ( m_hFileHandle == FILESYSTEM_INVALID_HANDLE )
		{
			Error( "Unable to read file %s!\n", m_pFileName );
			return 0;
		}
		if ( m_nOffset != 0 )
		{
			g_pFullFileSystem->Seek( m_hFileHandle, m_nOffset, FILESYSTEM_SEEK_HEAD );
		}
	}

	char *pReadPoint = (char*)Base() + nReadOffset;
	int nBytesRead = g_pFullFileSystem->Read( pReadPoint, nBytesToRead, m_hFileHandle );
	if ( nBytesRead != nBytesToRead )
	{
		// Since max put is a guess at the start, 
		// we need to shrink it based on the actual # read
		if ( m_nMaxPut > TellGet() + nReadOffset + nBytesRead )
		{
			m_nMaxPut = TellGet() + nReadOffset + nBytesRead;
		}
	}

	if ( nReadOffset + nBytesRead < Size() )
	{
		// This is necessary to deal with auto-NULL terminiation
		pReadPoint[nBytesRead] = 0;
	}

	return nBytesRead;
}


//-----------------------------------------------------------------------------
// Load up more of the stream when we overflow
//-----------------------------------------------------------------------------
bool CUtlStreamBuffer::StreamGetOverflow( int nSize )
{
	if ( !IsValid() || !IsReadOnly() )
		return false;

	// Shift the unread bytes down
	// NOTE: Can't use the partial overlap path if we're seeking. We'll 
	// get negative sizes passed in if we're seeking.
	int nUnreadBytes;
	bool bHasPartialOverlap = ( nSize >= 0 ) && ( TellGet() >= m_nOffset ) && ( TellGet() <= m_nOffset + Size() );
	if ( bHasPartialOverlap )
	{
		nUnreadBytes = Size() - ( TellGet() - m_nOffset );
		if ( ( TellGet() != m_nOffset ) && ( nUnreadBytes > 0 ) )
		{
			memmove( Base(), (const char*)Base() + TellGet() - m_nOffset, nUnreadBytes );
		}
	}
	else
	{
		m_nOffset = TellGet();
		g_pFullFileSystem->Seek( m_hFileHandle, m_nOffset, FILESYSTEM_SEEK_HEAD );
		nUnreadBytes = 0;
	}

	// Make sure the allocated size is at least as big as the requested size
	if ( nSize > 0 )
	{
		GrowAllocatedSize( nSize );
	}

	int nBytesToRead = Size() - nUnreadBytes;
	int nBytesRead = ReadBytesFromFile( nBytesToRead, nUnreadBytes );
	if ( nBytesRead == 0 )
		return false;

	m_nOffset = TellGet();
	return ( nBytesRead + nUnreadBytes >= nSize ); 
}


//-----------------------------------------------------------------------------
// open file unless already failed to open
//-----------------------------------------------------------------------------
FileHandle_t CUtlStreamBuffer::OpenFile( const char *pFileName, const char *pPath )
{
	if ( m_Error & FILE_OPEN_ERROR )
		return FILESYSTEM_INVALID_HANDLE;

	char openflags[ 3 ] = "xx";
	openflags[ 0 ] = IsReadOnly() ? 'r' : 'w';
	openflags[ 1 ] = IsText() && !ContainsCRLF() ? 't' : 'b';

	FileHandle_t fh = g_pFullFileSystem->Open( pFileName, openflags, pPath );
	if( fh == FILESYSTEM_INVALID_HANDLE )
	{
		m_Error	|= FILE_OPEN_ERROR;
	}

	return fh;
}