forked from UglyToad/PdfPig
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReadHelper.cs
More file actions
355 lines (296 loc) · 9.95 KB
/
ReadHelper.cs
File metadata and controls
355 lines (296 loc) · 9.95 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
namespace UglyToad.PdfPig.Core
{
using System;
using System.Buffers.Text;
using System.Collections.Generic;
using System.Text;
#if NET8_0_OR_GREATER
using System.Text.Unicode;
#endif
/// <summary>
/// Helper methods for reading from PDF files.
/// </summary>
public static class ReadHelper
{
/// <summary>
/// The line-feed '\n' character.
/// </summary>
public const byte AsciiLineFeed = 10;
/// <summary>
/// The carriage return '\r' character.
/// </summary>
public const byte AsciiCarriageReturn = 13;
private static readonly HashSet<int> EndOfNameCharacters =
[
' ',
AsciiCarriageReturn,
AsciiLineFeed,
9,
'>',
'<',
'[',
'/',
']',
')',
'(',
0,
'\f'
];
/// <summary>
/// Read a string from the input until a newline.
/// </summary>
public static string ReadLine(IInputBytes bytes)
{
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
if (bytes.IsAtEnd())
{
throw new InvalidOperationException("Error: End-of-File, expected line");
}
var buffer = new StringBuilder(11);
byte c = 0;
while (bytes.MoveNext())
{
c = bytes.CurrentByte;
// CR and LF are valid EOLs
if (IsEndOfLine(c))
{
break;
}
buffer.Append((char)c);
}
// CR+LF is also a valid EOL
if (IsCarriageReturn(c) && IsLineFeed(bytes.Peek()))
{
bytes.MoveNext();
}
return buffer.ToString();
}
/// <summary>
/// Skip any whitespace characters.
/// </summary>
public static void SkipSpaces(IInputBytes bytes)
{
const int commentCharacter = 37;
bytes.MoveNext();
byte c = bytes.CurrentByte;
while (IsWhitespace(c) || c == 37)
{
if (c == commentCharacter)
{
// skip past the comment section
bytes.MoveNext();
c = bytes.CurrentByte;
while (!IsEndOfLine(c))
{
bytes.MoveNext();
c = bytes.CurrentByte;
}
}
else
{
bytes.MoveNext();
c = bytes.CurrentByte;
}
}
if (!bytes.IsAtEnd())
{
bytes.Seek(bytes.CurrentOffset - 1);
}
}
/// <summary>
/// Whether the given character value is the end of a PDF Name token.
/// </summary>
public static bool IsEndOfName(int ch)
{
return EndOfNameCharacters.Contains(ch);
}
/// <summary>
/// Determines if a character is whitespace or not, this includes newlines.
/// </summary>
/// <remarks>
/// These values are specified in table 1 (page 12) of ISO 32000-1:2008.
/// </remarks>
public static bool IsWhitespace(byte c)
{
return c is 0 or 32 or AsciiLineFeed or AsciiCarriageReturn or 9 or 12;
}
/// <summary>
/// Whether the character is an end of line character.
/// </summary>
public static bool IsEndOfLine(char c) => IsEndOfLine((byte) c);
/// <summary>
/// Whether the character is an end of line character.
/// </summary>
public static bool IsEndOfLine(byte b)
{
return IsLineFeed(b) || IsCarriageReturn(b);
}
/// <summary>
/// Whether the character is an line feed '\n' character.
/// </summary>
public static bool IsLineFeed(byte? c)
{
return AsciiLineFeed == c;
}
/// <summary>
/// Whether the character is a carriage return '\r' character.
/// </summary>
public static bool IsCarriageReturn(byte c)
{
return AsciiCarriageReturn == c;
}
/// <summary>
/// Whether the given string is at this position in the input.
/// Resets to the current offset once read.
/// </summary>
public static bool IsString(IInputBytes bytes, string s)
{
bool found = true;
var startOffset = bytes.CurrentOffset;
foreach (var c in s)
{
if (bytes.CurrentByte != c)
{
found = false;
break;
}
bytes.MoveNext();
}
bytes.Seek(startOffset);
return found;
}
/// <summary>
/// Whether the given string is at this position in the input.
/// Resets to the current offset once read.
/// </summary>
public static bool IsString(IInputBytes bytes, ReadOnlySpan<byte> s)
{
bool found = true;
var startOffset = bytes.CurrentOffset;
foreach (var c in s)
{
if (bytes.CurrentByte != c)
{
found = false;
break;
}
bytes.MoveNext();
}
bytes.Seek(startOffset);
return found;
}
/// <summary>
/// Read a long from the input.
/// </summary>
public static long ReadLong(IInputBytes bytes)
{
SkipSpaces(bytes);
Span<byte> buffer = stackalloc byte[19]; // max formatted uint64 length
ReadNumberAsUtf8Bytes(bytes, buffer, out int bytesRead);
ReadOnlySpan<byte> longBytes = buffer.Slice(0, bytesRead);
if (Utf8Parser.TryParse(longBytes, out long result, out _))
{
return result;
}
else
{
bytes.Seek(bytes.CurrentOffset - bytesRead);
throw new InvalidOperationException($"Error: Expected a long type at offset {bytes.CurrentOffset}, instead got \'{OtherEncodings.BytesAsLatin1String(longBytes)}\'");
}
}
/// <summary>
/// Whether the given value is a digit or not.
/// </summary>
public static bool IsDigit(int c)
{
return c >= '0' && c <= '9';
}
/// <summary>
/// Read an int from the input.
/// </summary>
public static int ReadInt(IInputBytes bytes)
{
if (bytes is null)
{
throw new ArgumentNullException(nameof(bytes));
}
SkipSpaces(bytes);
Span<byte> buffer = stackalloc byte[10]; // max formatted uint32 length
ReadNumberAsUtf8Bytes(bytes, buffer, out int bytesRead);
var intBytes = buffer.Slice(0, bytesRead);
if (Utf8Parser.TryParse(intBytes, out int result, out _))
{
return result;
}
else
{
bytes.Seek(bytes.CurrentOffset - bytesRead);
throw new PdfDocumentFormatException($"Error: Expected an integer type at offset {bytes.CurrentOffset}, instead got \'{OtherEncodings.BytesAsLatin1String(intBytes)}\'");
}
}
/// <summary>
/// Whether the given character value is a valid hex value.
/// </summary>
public static bool IsHex(byte b) => IsHex((char) b);
/// <summary>
/// Whether the given character value is a valid hex value.
/// </summary>
public static bool IsHex(char ch)
{
#if NET8_0_OR_GREATER
return char.IsAsciiHexDigit(ch);
#else
return char.IsDigit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
#endif
}
/// <summary>
/// Whether the given input bytes are valid UTF8.
/// </summary>
public static bool IsValidUtf8(byte[] input)
{
#if NET8_0_OR_GREATER
return Utf8.IsValid(input);
#else
try
{
var d = Encoding.UTF8.GetDecoder();
var charLength = d.GetCharCount(input, 0, input.Length);
var chars = new char[charLength];
d.Convert(input, 0, input.Length, chars, 0, charLength, true, out _, out _, out _);
return true;
}
catch (Exception)
{
return false;
}
#endif
}
private static void ReadNumberAsUtf8Bytes(IInputBytes reader, scoped Span<byte> buffer, out int bytesRead)
{
int position = 0;
byte lastByte;
while (reader.MoveNext() && (lastByte = reader.CurrentByte) != ' ' &&
lastByte != AsciiLineFeed &&
lastByte != AsciiCarriageReturn &&
lastByte != 60 && // see sourceforge bug 1714707
lastByte != '[' && // PDFBOX-1845
lastByte != '(' && // PDFBOX-2579
lastByte != 0)
{
if (position >= buffer.Length)
{
throw new InvalidOperationException($"Number \'{OtherEncodings.BytesAsLatin1String(buffer.Slice(0, position))}\' is getting too long, stop reading at offset {reader.CurrentOffset}");
}
buffer[position++] = lastByte;
}
if (!reader.IsAtEnd())
{
reader.Seek(reader.CurrentOffset - 1);
}
bytesRead = position;
}
}
}