summaryrefslogtreecommitdiffstats
path: root/source/core/slang-stream.cpp
blob: b5eef1d9bf50ed8f27cc0777a912d7f0e39025bd (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
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
#include "slang-stream.h"
#ifdef _WIN32
#include <share.h>
#endif
#include "slang-io.h"

namespace Slang
{

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! FileStream !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

FileStream::FileStream(const String& fileName, FileMode fileMode)
{
	_init(fileName, fileMode, fileMode==FileMode::Open?FileAccess::Read:FileAccess::Write, FileShare::None);
}

FileStream::FileStream(const String& fileName, FileMode fileMode, FileAccess access, FileShare share)
{
	_init(fileName, fileMode, access, share);
}

void FileStream::_init(const String& fileName, FileMode fileMode, FileAccess access, FileShare share)
{
	const wchar_t * mode = L"rt";
	const char* modeMBCS = "rt";
	switch (fileMode)
	{
	case FileMode::Create:
		if (access == FileAccess::Read)
			throw ArgumentException("Read-only access is incompatible with Create mode.");
		else if (access == FileAccess::ReadWrite)
		{
			mode = L"w+b";
			modeMBCS = "w+b";
			this->m_fileAccess = FileAccess::ReadWrite;
		}
		else
		{
			mode = L"wb";
			modeMBCS = "wb";
			this->m_fileAccess = FileAccess::Write;
		}
		break;
	case FileMode::Open:
		if (access == FileAccess::Read)
		{
			mode = L"rb";
			modeMBCS = "rb";
			this->m_fileAccess = FileAccess::Read;
		}
		else if (access == FileAccess::ReadWrite)
		{
			mode = L"r+b";
			modeMBCS = "r+b";
			this->m_fileAccess = FileAccess::ReadWrite;
		}
		else
		{
			mode = L"wb";
			modeMBCS = "wb";
			this->m_fileAccess = FileAccess::Write;
		}
		break;
	case FileMode::CreateNew:
		if (File::exists(fileName))
		{
			throw IOException("Failed opening '" + fileName + "', file already exists.");
		}
		if (access == FileAccess::Read)
			throw ArgumentException("Read-only access is incompatible with Create mode.");
		else if (access == FileAccess::ReadWrite)
		{
			mode = L"w+b";
			this->m_fileAccess = FileAccess::ReadWrite;
		}
		else
		{
			mode = L"wb";
			this->m_fileAccess = FileAccess::Write;
		}
		break;
	case FileMode::Append:
		if (access == FileAccess::Read)
			throw ArgumentException("Read-only access is incompatible with Append mode.");
		else if (access == FileAccess::ReadWrite)
		{
			mode = L"a+b";
			this->m_fileAccess = FileAccess::ReadWrite;
		}
		else
		{
			mode = L"ab";
			this->m_fileAccess = FileAccess::Write;
		}
		break;
	default:
		break;
	}
#ifdef _WIN32
    int shFlag = _SH_DENYRW;
    switch (share)
	{
	case FileShare::None:
		shFlag = _SH_DENYRW;
		break;
	case FileShare::ReadOnly:
		shFlag = _SH_DENYWR;
		break;
	case FileShare::WriteOnly:
		shFlag = _SH_DENYRD;
		break;
	case FileShare::ReadWrite:
		shFlag = _SH_DENYNO;
		break;
	default:
		throw ArgumentException("Invalid file share mode.");
		break;
	}
    if (share == FileShare::None)
#pragma warning(suppress:4996)
        m_handle = _wfopen(fileName.toWString(), mode);
    else
		m_handle = _wfsopen(fileName.toWString(), mode, shFlag);
#else
	m_handle = fopen(fileName.getBuffer(), modeMBCS);
#endif
	if (!m_handle)
	{
		throw IOException("Cannot open file '" + fileName + "'");
	}
}

FileStream::~FileStream()
{
	close();
}

Int64 FileStream::getPosition()
{
#if defined(_WIN32) || defined(__CYGWIN__)
	fpos_t pos;
	fgetpos(m_handle, &pos);
	return pos;
#elif defined(__APPLE__)
	return ftell(m_handle);
#else 
	fpos64_t pos;
	fgetpos64(m_handle, &pos);
	return *(Int64*)(&pos);
#endif
}
void FileStream::seek(SeekOrigin origin, Int64 offset)
{
	int _origin;
	switch (origin)
	{
	case SeekOrigin::Start:
		_origin = SEEK_SET;
		m_endReached = false;
		break;
	case SeekOrigin::End:
		_origin = SEEK_END;
        // JS TODO: This doesn't seem right, the offset can mean it's not at the end
		m_endReached = true;
		break;
	case SeekOrigin::Current:
		_origin = SEEK_CUR;
		m_endReached = false;
		break;
	default:
		throw NotSupportedException("Unsupported seek origin.");
		break;
	}
#ifdef _WIN32
	int rs = _fseeki64(m_handle, offset, _origin);
#else
	int rs = fseek(m_handle, (int)offset, _origin);
#endif
	if (rs != 0)
	{
		throw IOException("FileStream seek failed.");
	}
}
Int64 FileStream::read(void* buffer, Int64 length)
{
	auto bytes = fread_s(buffer, (size_t)length, 1, (size_t)length, m_handle);
	if (bytes == 0 && length > 0)
	{
		if (!feof(m_handle))
			throw IOException("FileStream read failed.");
		else if (m_endReached)
			throw EndOfStreamException("End of file is reached.");
		m_endReached = true;
	}
	return (int)bytes;
}
Int64 FileStream::write(const void* buffer, Int64 length)
{
	auto bytes = (Int64)fwrite(buffer, 1, (size_t)length, m_handle);
	if (bytes < length)
	{
		throw IOException("FileStream write failed.");
	}
	return bytes;
}
bool FileStream::canRead()
{
	return ((int)m_fileAccess & (int)FileAccess::Read) != 0;
}
bool FileStream::canWrite()
{
	return ((int)m_fileAccess & (int)FileAccess::Write) != 0;
}
void FileStream::close()
{
	if (m_handle)
	{
		fclose(m_handle);
		m_handle = 0;
	}
}
bool FileStream::isEnd()
{
	return m_endReached;
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! MemoryStreamBase !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

void MemoryStreamBase::seek(SeekOrigin origin, Int64 offset)
{
    Int64 pos = 0;
    switch (origin)
    {
        case SeekOrigin::Start:
            pos = offset;
            break;
        case SeekOrigin::End:
            pos = Int64(m_contentsSize) + offset;
            break;
        case SeekOrigin::Current:
            pos = Int64(m_position) + offset;
            break;
        default:
            throw NotSupportedException("Unsupported seek origin.");
            break;
    }

    m_atEnd = false;

    // Clamp to the valid range
    pos = (pos < 0) ? 0 : pos;
    pos = (pos > Int64(m_contentsSize)) ? Int64(m_contentsSize) : pos;

    m_position = UInt(pos);
}

Int64 MemoryStreamBase::read(void* buffer, Int64 length)
{
    if (!canRead())
    {
        throw IOException("Cannot read this stream.");
    }

    const Int64 maxRead = Int64(m_contentsSize - m_position);

    if (maxRead == 0 && length > 0)
    {
        m_atEnd = true;
        throw EndOfStreamException("End of file is reached.");
    }

    length = length > maxRead ? maxRead : length;

    ::memcpy(buffer, m_contents + m_position, size_t(length));
    m_position += UInt(length);
    return maxRead;
}

// !!!!!!!!!!!!!!!!!!!!!!!!!!!!! OwnedMemoryStream !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Int64 OwnedMemoryStream::write(const void * buffer, Int64 length)
{
    if (!canWrite())
    {
        throw IOException("Cannot write this stream.");
    }

    if (m_position == m_ownedContents.getCount())
    {
        m_ownedContents.addRange((const uint8_t*)buffer, UInt(length));
    }
    else
    {
        m_ownedContents.insertRange(m_position, (const uint8_t*)buffer, UInt(length));
    }

    m_contents = m_ownedContents.getBuffer();
    m_contentsSize = ptrdiff_t(m_ownedContents.getCount());

    m_atEnd = false;

    m_position += ptrdiff_t(length);
    return length;
}

} // namespace Slang