forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMemoryMappedFileStreamReader.cs
More file actions
368 lines (316 loc) · 12 KB
/
MemoryMappedFileStreamReader.cs
File metadata and controls
368 lines (316 loc) · 12 KB
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
#nullable disable
// Copyright (c) Microsoft Corporation. All rights reserved.
// This file is best viewed using outline mode (Ctrl-M Ctrl-O)
//
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
//
using System;
using System.IO;
using System.Text; // For StringBuilder.
using System.Threading;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using DeferedStreamLabel = FastSerialization.StreamLabel;
using System.Diagnostics;
namespace FastSerialization
{
internal class MemoryMappedFileStreamReader : IStreamReader
{
const int BlockCopyCapacity = 10 * 1024 * 1024;
private MemoryMappedFile _file;
private long _fileLength;
private bool _leaveOpen;
private MemoryMappedViewAccessor _view;
private IntPtr _viewAddress;
private long _viewOffset;
private long _capacity;
private long _offset;
public MemoryMappedFileStreamReader(string mapName, long length)
#pragma warning disable CA1416
: this(MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read), length, leaveOpen: false)
#pragma warning restore CA1416
{
}
public MemoryMappedFileStreamReader(MemoryMappedFile file, long length, bool leaveOpen)
{
_file = file;
_fileLength = length;
_leaveOpen = leaveOpen;
if (IntPtr.Size == 4)
{
_capacity = Math.Min(_fileLength, BlockCopyCapacity);
}
else
{
_capacity = _fileLength;
}
_view = File.CreateViewAccessor(0, _capacity, MemoryMappedFileAccess.Read);
_viewAddress = _view.SafeMemoryMappedViewHandle.DangerousGetHandle();
}
public static MemoryMappedFileStreamReader CreateFromFile(string path)
{
#pragma warning disable SN0001 // - Won't run on Switch
long capacity = new FileInfo(path).Length;
#pragma warning restore SN0001
MemoryMappedFile file = MemoryMappedFile.CreateFromFile(path, FileMode.Open, Guid.NewGuid().ToString("N"), capacity, MemoryMappedFileAccess.Read);
return new MemoryMappedFileStreamReader(file, capacity, leaveOpen: false);
}
public DeferedStreamLabel Current
{
get
{
return checked((DeferedStreamLabel)(_viewOffset + _offset));
}
}
public long Length => _fileLength;
protected MemoryMappedFile File
{
get
{
var result = _file;
if (result == null)
{
throw new ObjectDisposedException(nameof(MemoryMappedFileStreamReader));
}
return result;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Seek(long offset)
{
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
// see if we can just change the offset
if (offset >= _viewOffset && offset < _viewOffset + _capacity)
{
_offset = offset - _viewOffset;
return;
}
// Have to move the view
_view.Dispose();
long availableInFile = _fileLength - offset;
long viewOffset = offset & ~0xFFFF;
long offsetInView = offset - viewOffset;
long viewLength = Math.Min(BlockCopyCapacity, availableInFile + offsetInView);
_view = _file.CreateViewAccessor(viewOffset, viewLength, MemoryMappedFileAccess.Read);
_viewAddress = _view.SafeMemoryMappedViewHandle.DangerousGetHandle();
_viewOffset = viewOffset;
_capacity = viewLength;
_offset = offsetInView;
}
public void Goto(DeferedStreamLabel label)
{
if (label < 0)
{
throw new ArgumentOutOfRangeException(nameof(label));
}
// see if we can just change the offset
Debug.Assert((long)label <= int.MaxValue);
int absoluteOffset = (int)label;
if (absoluteOffset >= _viewOffset && absoluteOffset < _viewOffset + _capacity)
{
_offset = (int)(absoluteOffset - _viewOffset);
return;
}
// Have to move the view
_view.Dispose();
long availableInFile = _fileLength - absoluteOffset;
long viewOffset = absoluteOffset & ~0xFFFF;
long offset = absoluteOffset - viewOffset;
long viewLength = Math.Min(BlockCopyCapacity, availableInFile + offset);
_view = _file.CreateViewAccessor(viewOffset, viewLength, MemoryMappedFileAccess.Read);
_viewAddress = _view.SafeMemoryMappedViewHandle.DangerousGetHandle();
_viewOffset = viewOffset;
_capacity = viewLength;
_offset = offset;
}
public void GotoSuffixLabel()
{
const int sizeOfSerializedStreamLabel = 4;
Goto((DeferedStreamLabel)(Length - sizeOfSerializedStreamLabel));
Goto(ReadLabel());
}
public unsafe void Read(byte[] data, int offset, int length)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (length > data.Length - offset)
{
throw new ArgumentNullException(nameof(length));
}
if (_offset + length > _capacity)
{
Resize(length);
}
Marshal.Copy((IntPtr)((byte*)_viewAddress + _offset), data, 0, length);
_offset += length;
}
public T Read<T>()
where T : struct
{
int size = Marshal.SizeOf<T>();
if (_offset + size > _capacity)
{
Resize(size);
}
T result;
#if NETSTANDARD1_3
byte[] rawData = new byte[size];
Read(rawData, 0, size);
unsafe
{
fixed (byte* rawDataPtr = rawData)
{
result = Marshal.PtrToStructure<T>((IntPtr)rawDataPtr);
}
}
#else
_view.Read(_offset, out result);
#endif
_offset += size;
return result;
}
public unsafe byte ReadByte()
{
if (_offset + sizeof(byte) > _capacity)
{
Resize(sizeof(byte));
}
var result = *((byte*)_viewAddress + _offset);
_offset += sizeof(byte);
return result;
}
public unsafe short ReadInt16()
{
if (_offset + sizeof(short) > _capacity)
{
Resize(sizeof(short));
}
var result = *(short*)((byte*)_viewAddress + _offset);
_offset += sizeof(short);
return result;
}
public unsafe int ReadInt32()
{
if (_offset + sizeof(int) > _capacity)
{
Resize(sizeof(int));
}
var result = *(int*)((byte*)_viewAddress + _offset);
_offset += sizeof(int);
return result;
}
public unsafe long ReadInt64()
{
if (_offset + sizeof(long) > _capacity)
{
Resize(sizeof(long));
}
var result = *(long*)((byte*)_viewAddress + _offset);
_offset += sizeof(long);
return result;
}
public DeferedStreamLabel ReadLabel()
{
return (DeferedStreamLabel)ReadInt32();
}
public unsafe string ReadString()
{
int charCount = ReadInt32();
if (charCount == -1)
{
return null;
}
string result = new string('\0', charCount);
fixed (char* chars = result)
{
Decoder decoder = Encoding.UTF8.GetDecoder();
int bytesUsed;
int charsUsed;
bool completed;
#if NETSTANDARD1_3
byte[] bytes = new byte[(int)Math.Min(int.MaxValue - 50, _capacity - _offset)];
Marshal.Copy(_viewAddress, bytes, 0, bytes.Length);
char[] charArray = new char[charCount];
decoder.Convert(bytes, 0, bytes.Length, charArray, 0, charArray.Length, false, out bytesUsed, out charsUsed, out completed);
Marshal.Copy(charArray, 0, (IntPtr)chars, charsUsed * sizeof(char));
#else
decoder.Convert((byte*)_viewAddress, (int)Math.Min(int.MaxValue - 50, _capacity - _offset), chars, charCount, false, out bytesUsed, out charsUsed, out completed);
#endif
_offset += bytesUsed;
if (!completed)
{
long availableInFile = _fileLength - _viewOffset - _offset;
Resize(checked((int)Math.Min(availableInFile, Encoding.UTF8.GetMaxByteCount(charCount - charsUsed))));
int finalBytesUsed;
int finalCharsUsed;
#if NETSTANDARD1_3
bytes = new byte[(int)Math.Min(int.MaxValue - 50, _capacity - _offset)];
Marshal.Copy(_viewAddress + bytesUsed, bytes, 0, bytes.Length);
charArray = new char[charCount - charsUsed];
decoder.Convert(bytes, 0, bytes.Length, charArray, 0, charArray.Length, true, out finalBytesUsed, out finalCharsUsed, out completed);
Marshal.Copy(charArray, 0, (IntPtr)(chars + charsUsed), finalCharsUsed * sizeof(char));
#else
decoder.Convert((byte*)_viewAddress + bytesUsed, (int)Math.Min(int.MaxValue - 50, _capacity - _offset), chars + charsUsed, charCount - charsUsed, true, out finalBytesUsed, out finalCharsUsed, out completed);
#endif
}
}
return result;
}
protected void Resize(int capacity)
{
// See if we can do nothing
long available = _capacity - _offset;
if (available >= capacity)
{
return;
}
// We can no longer use the current view, so go ahead and dispose of it
_view.Dispose();
// See if the underlying file is large enough
long availableInFile = _fileLength - _viewOffset - _offset;
if (availableInFile < capacity)
{
throw new InvalidOperationException("Cannot create a view outside the bounds of the file.");
}
long viewOffset = (_viewOffset + _offset) & ~0xFFFF;
long offset = (_viewOffset + _offset) - viewOffset;
long viewLength = Math.Max(Math.Min(BlockCopyCapacity, availableInFile + offset), capacity + offset);
_view = _file.CreateViewAccessor(viewOffset, viewLength, MemoryMappedFileAccess.Read);
_viewAddress = _view.SafeMemoryMappedViewHandle.DangerousGetHandle();
_viewOffset = viewOffset;
_capacity = viewLength;
_offset = offset;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_viewAddress = IntPtr.Zero;
Interlocked.Exchange(ref _view, null)?.Dispose();
var file = Interlocked.Exchange(ref _file, null);
if (!_leaveOpen)
{
file?.Dispose();
}
}
}
}
}