-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparse.go
548 lines (463 loc) · 10.6 KB
/
parse.go
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package pdf
import (
"errors"
"strconv"
)
// Returns an Object and the number of bytes consumed
// if err != nil, the int is the offset in the slice
// where the error was discovered. The object will
// be returned as far as it was completed (to allow
// for inspection)
type parseFn func(slice []byte) (Object, int, error)
func parseObject(slice []byte) (Object, int, error) {
start, ok := nextNonWhitespace(slice)
if !ok {
return nil, 0, errors.New("expected a non-whitespace char")
}
var parser parseFn
maybeObjectReference := false
maybeStream := false
// determine the object type
// except for Stream §7.3.8
// streams start as dictionaries
switch slice[start] {
case 't', 'f':
// Boolean §7.3.2
parser = parseBoolean
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-':
// Integer §7.3.3
// Real §7.3.3
// could also be the start of an object reference
parser = parseNumeric
maybeObjectReference = true
case '(':
// String §7.3.4
parser = parseLiteralString
case '/':
// Name §7.3.5
// println("Name")
parser = parseName
case '[':
// Array §7.3.6
parser = parseArray
case '<':
if slice[start+1] == '<' {
// Dictionary §7.3.7
// println("Dictionary")
parser = parseDictionary
maybeStream = true
} else {
// String §7.3.4
parser = parseHexadecimalString
}
case 'n':
// Null §7.3.9
parser = parseNull
default:
panic(string(slice[start]))
}
object, n, err := parser(slice[start:])
if maybeObjectReference {
objectref, n2, err := parseObjectReference(slice[start:])
if err == nil {
object = objectref
n = n2
}
}
// handle streams
if maybeStream {
n2, isStream := match(slice[start+n:], "stream")
if isStream {
n += n2
// consume end of line (§7.3.8.1 paragraph after example)
switch slice[start+n] {
case 13: // carriage return
n++
if slice[start+n] != '\n' {
return object, start + n + 1, errors.New("end of line marker cannot have only a carriage return")
}
case '\n': // new line
default:
return object, start + n + 1, errors.New("expected end of line marker")
}
n++
dict, isDictionary := object.(Dictionary)
if !isDictionary {
return object, start + n, errors.New("expected a Dictionary")
}
var streamLengthInteger Integer
streamLengthInteger, ok = dict["Length"].(Integer)
if !ok {
object = Stream{
Dictionary: dict,
Stream: slice[start+n:],
}
} else {
streamLength := int(streamLengthInteger)
object = Stream{
Dictionary: dict,
Stream: slice[start+n : start+n+streamLength],
}
n += streamLength
n2, ok = match(slice[start+n:], "endstream")
n += n2
if !ok {
return object, start + n, errors.New("expected 'endstream'")
}
}
}
}
return object, start + n, err
}
// for tokenized things, returns the next token
func nextToken(slice []byte) ([]byte, int) {
// whitespace:
// null, tab, line feed, form feed, carriage return, or space
// §7.2.2 Table 1
// delimiters:
// (, ), <, >, [, ], {, }, /, %
// §7.2.2 Table 2
var begin, end int
var ok bool
begin, ok = nextNonWhitespace(slice)
if !ok {
begin = 0
}
for end = begin; end < len(slice); end++ {
if isWhitespace(slice[end]) || isDelimiter(slice[end]) {
return slice[begin:end], end
}
}
return slice[begin:], len(slice)
}
func isDelimiter(char byte) bool {
switch char {
case 40, 41, 60, 62, 91, 93, 123, 125, 47, 37: // delimiters
return true
}
return false
}
func isWhitespace(char byte) bool {
switch char {
case 0, 9, 10, 12, 13, 32: // whitespace
return true
}
return false
}
func isHexDigit(char byte) bool {
switch char {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F',
'a', 'b', 'c', 'd', 'e', 'f':
return true
}
return false
}
func nextNonWhitespace(slice []byte) (int, bool) {
for i := 0; i < len(slice); i++ {
if !isWhitespace(slice[i]) {
return i, true
}
}
return 0, false
}
func match(slice []byte, toMatch string) (int, bool) {
token, n := nextToken(slice)
if len(token) != len(toMatch) {
return 0, false
}
for i, char := range token {
if char != toMatch[i] {
return n + i, false
}
}
return n, true
}
func index(slice []byte, toFind byte) (int, bool) {
for i := 0; i < len(slice); i++ {
if slice[i] == toFind {
return i, true
}
}
return 0, false
}
func parseLiteralString(slice []byte) (Object, int, error) {
decoded := make([]byte, len(slice))
decodedIndex := 0
if slice[0] != '(' {
return String(decoded[:decodedIndex]), 0, errors.New("not a literal string")
}
parens := 0
i := 0
for i < len(slice) {
include := true
switch slice[i] {
case '(':
if parens == 0 {
include = false
}
parens++
case ')':
parens--
if parens == 0 {
return String(decoded[:decodedIndex]), i + 1, nil
}
include = true
case '\n':
if slice[i-1] == '\\' {
decodedIndex--
include = false
}
}
if include {
decoded[decodedIndex] = slice[i]
decodedIndex++
}
i++
}
return String(decoded[:decodedIndex]), i, errors.New("couldn't find end of string")
}
// returned int is the length of slice consumed
func parseDictionary(slice []byte) (Object, int, error) {
dict := make(Dictionary)
if slice[0] != '<' && slice[1] != '<' {
return dict, 0, errors.New("not a dictionary")
}
i := 2
for i < len(slice) {
// skip whitespace
n, ok := nextNonWhitespace(slice[i:])
if !ok {
return dict, i, errors.New("expected a non-whitespace char")
}
i += n
// check to see if end
if slice[i] == '>' && slice[i+1] == '>' {
i += 2
break
}
// get the key
var name Object
var err error
name, n, err = parseName(slice[i:])
if err != nil {
return dict, i + n, err
}
i += n
var key Name
key, ok = name.(Name)
if !ok {
return dict, i, errors.New("unable to cast Name")
}
// get the value
var value Object
value, n, err = parseObject(slice[i:])
if err != nil {
return dict, i, err
}
i += n
// set the key/value pair
dict[key] = value
}
return dict, i, nil
}
func parseName(slice []byte) (Object, int, error) {
name := make([]byte, 0, len(slice))
if slice[0] != '/' {
return Name(name), 0, errors.New("not a name")
}
i := 1
for i < len(slice) {
if isDelimiter(slice[i]) || isWhitespace(slice[i]) {
break
}
switch slice[i] {
case '#':
char, err := strconv.ParseUint(string(slice[i+1:i+3]), 16, 8)
if err != nil {
return Name(name), i, err
}
name = append(name, byte(char))
i += 2
default:
name = append(name, slice[i])
}
i++
}
return Name(name), i, nil
}
func parseBoolean(slice []byte) (Object, int, error) {
n, ok := match(slice, "true")
if ok {
return Boolean(true), n, nil
}
n, ok = match(slice, "false")
if ok {
return Boolean(false), n, nil
}
return Boolean(false), 0, errors.New("not a boolean")
}
// returns Integer when integer, Real when real
func parseNumeric(slice []byte) (Object, int, error) {
token, n := nextToken(slice)
isInteger := true
for _, char := range token {
if char == '.' {
isInteger = false
break
}
}
if isInteger {
integer, err := strconv.ParseInt(string(token), 10, 0)
if err != nil {
return Integer(integer), n, err
}
return Integer(integer), n, nil
}
real, err := strconv.ParseFloat(string(token), 64)
if err != nil {
return Real(0), n, err
}
return Real(real), n, nil
}
func parseHexadecimalString(slice []byte) (Object, int, error) {
hex := make(String, 0, int(len(slice)/2))
if slice[0] != '<' {
return hex, 0, errors.New("not a hexadecimal string")
}
i := 1
for i < len(slice) {
if slice[i] == '>' {
i++
break
}
if isHexDigit(slice[i]) && isHexDigit(slice[i+1]) {
b, err := strconv.ParseUint(string(slice[i:i+2]), 16, 8)
if err != nil {
return hex, i, err
}
hex = append(hex, byte(b))
i += 2
continue
}
if isHexDigit(slice[i]) && slice[i+1] == '>' {
b, err := strconv.ParseUint(string(slice[i])+"0", 16, 8)
if err != nil {
return hex, i, err
}
hex = append(hex, byte(b))
i += 2
break
}
}
return hex, i, nil
}
func parseArray(slice []byte) (Object, int, error) {
array := make(Array, 0)
if slice[0] != '[' {
return array, 0, errors.New("not an array")
}
i := 1
for i < len(slice) {
if isWhitespace(slice[i]) {
i++
continue
}
if slice[i] == ']' {
return array, i + 1, nil
}
object, n, err := parseObject(slice[i:])
if err != nil {
return array, i, err
}
i += n
array = append(array, object)
}
return array, i, errors.New("end of array not found")
}
func parseNull(slice []byte) (Object, int, error) {
n, ok := match(slice, "null")
if ok {
return Null{}, n, nil
}
return Null{}, 0, errors.New("not a Null")
}
func parseObjectReference(slice []byte) (Object, int, error) {
objref := ObjectReference{}
i := 0
objectNumber, n, err := parseNumeric(slice[i:])
i += n
if err != nil {
return objref, i, err
}
integer, ok := objectNumber.(Integer)
if !ok {
return objref, i, errors.New("expected object number not an integer")
}
objref.ObjectNumber = uint(integer)
var generationNumber Object
generationNumber, n, err = parseNumeric(slice[i:])
i += n
if err != nil {
return objref, i, err
}
integer, ok = generationNumber.(Integer)
if !ok {
return objref, i, errors.New("expected generation number not an integer")
}
objref.GenerationNumber = uint(integer)
n, ok = match(slice[i:], "R")
i += n
if !ok {
return objref, i, errors.New("could not find end of object reference")
}
return objref, i, nil
}
func parseIndirectObject(slice []byte) (Object, int, error) {
i := 0
// Object Number
token, n := nextToken(slice[i:])
objectNumber, err := strconv.ParseUint(string(token), 10, 64)
i += n
if err != nil {
return nil, i, err
}
var io IndirectObject
io.ObjectNumber = uint(objectNumber)
// Generation Number
token, n = nextToken(slice[i:])
generationNumber, err := strconv.ParseUint(string(token), 10, 64)
i += n
if err != nil {
return nil, i, err
}
io.GenerationNumber = uint(generationNumber)
// "obj"
var ok bool
n, ok = match(slice[i:], "obj")
i += n
if !ok {
return io, i, errors.New("could not find 'obj'")
}
// the object
var object Object
object, n, err = parseObject(slice[i:])
i += n
io.Object = object
if err != nil {
return io, i, err
}
// stream objects might not have determinable lengths, and so cannot be fully parsed
if stream, isStream := object.(Stream); isStream {
if _, isObjectRef := stream.Dictionary["Length"].(ObjectReference); isObjectRef {
return io, i, nil
}
}
// "endobj"
n, ok = match(slice[i:], "endobj")
i += n
if !ok {
return io, i, errors.New("could not find 'endobj'")
}
return io, i, nil
}