Debian Codegraph @

binary.go

raw
1 package parse
2
3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "sync"
10 )
11
12 const PageSize = 4096
13
14 type IBinaryReader interface {
15 Bytes([]byte, int64, int64) ([]byte, error)
16 Len() int64
17 Close() error
18 }
19
20 type binaryReaderBytes struct {
21 data []byte
22 closer io.Closer
23 }
24
25 func newBinaryReaderBytes(data []byte) *binaryReaderBytes {
26 return &binaryReaderBytes{data: data}
27 }
28
29 // Close closes the reader.
30 func (r *binaryReaderBytes) Close() error {
31 if r.closer != nil {
32 return r.closer.Close()
33 }
34 return nil
35 }
36
37 // Len returns the length of the underlying memory-mapped file.
38 func (r *binaryReaderBytes) Len() int64 {
39 return int64(len(r.data))
40 }
41
42 func (r *binaryReaderBytes) Bytes(b []byte, n, off int64) ([]byte, error) {
43 var err error
44 if off < 0 || n < 0 {
45 return nil, fmt.Errorf("bytes: invalid range %d--%d", off, off+n)
46 } else if n == 0 {
47 return nil, nil
48 } else if int64(len(r.data)) <= off {
49 return nil, io.EOF
50 } else if int64(len(r.data))-off < n {
51 n = int64(len(r.data)) - off
52 err = io.EOF
53 }
54
55 data := r.data[off : off+n : off+n]
56 if b == nil {
57 return data, err
58 }
59 copy(b, data)
60 return b[:len(data)], err
61 }
62
63 type binaryReaderReader struct {
64 r io.Reader
65 pos, size int64
66 }
67
68 func newBinaryReaderReader(r io.Reader, n int64) *binaryReaderReader {
69 return &binaryReaderReader{r, 0, n}
70 }
71
72 // Close closes the reader.
73 func (r *binaryReaderReader) Close() error {
74 if closer, ok := r.r.(io.Closer); ok {
75 return closer.Close()
76 }
77 return nil
78 }
79
80 // Len returns the length of the file.
81 func (r *binaryReaderReader) Len() int64 {
82 return r.size
83 }
84
85 func (r *binaryReaderReader) Bytes(b []byte, n, off int64) ([]byte, error) {
86 if off != r.pos {
87 return nil, errors.New("reader: does not implement io.Seeker or io.ReaderAt")
88 } else if n == 0 {
89 return nil, nil
90 } else if b == nil {
91 b = make([]byte, n)
92 }
93
94 for i := 0; i < int(n); {
95 m, err := r.r.Read(b[i:])
96 r.pos += int64(m)
97 i += m
98 if err != nil {
99 return b[:i], err
100 } else if m == 0 {
101 return b[:i], errors.New("reader: could not read all bytes")
102 }
103 }
104 return b, nil
105 }
106
107 type binaryReaderSeeker struct {
108 r io.ReadSeeker
109 size int64
110 mu sync.Mutex
111 }
112
113 func newBinaryReaderSeeker(r io.ReadSeeker, n int64) *binaryReaderSeeker {
114 return &binaryReaderSeeker{r, n, sync.Mutex{}}
115 }
116
117 // Close closes the reader.
118 func (r *binaryReaderSeeker) Close() error {
119 if closer, ok := r.r.(io.Closer); ok {
120 return closer.Close()
121 }
122 return nil
123 }
124
125 // Len returns the length of the file.
126 func (r *binaryReaderSeeker) Len() int64 {
127 return r.size
128 }
129
130 func (r *binaryReaderSeeker) Bytes(b []byte, n, off int64) ([]byte, error) {
131 if n == 0 {
132 return nil, nil
133 } else if b == nil {
134 b = make([]byte, n)
135 }
136
137 r.mu.Lock()
138 if _, err := r.r.Seek(off, 0); err != nil {
139 r.mu.Unlock()
140 return nil, err
141 }
142 for i := 0; i < int(n); {
143 m, err := r.r.Read(b[i:])
144 i += m
145 if err != nil {
146 r.mu.Unlock()
147 return b[:i], err
148 } else if m == 0 {
149 r.mu.Unlock()
150 return b[:i], errors.New("reader: could not read all bytes")
151 }
152 }
153 r.mu.Unlock()
154
155 return b, nil
156 }
157
158 type binaryReaderReaderAt struct {
159 r io.ReaderAt
160 size int64
161 }
162
163 func newBinaryReaderReaderAt(r io.ReaderAt, n int64) *binaryReaderReaderAt {
164 return &binaryReaderReaderAt{r, n}
165 }
166
167 // Close closes the reader.
168 func (r *binaryReaderReaderAt) Close() error {
169 if closer, ok := r.r.(io.Closer); ok {
170 return closer.Close()
171 }
172 return nil
173 }
174
175 // Len returns the length of the file.
176 func (r *binaryReaderReaderAt) Len() int64 {
177 return r.size
178 }
179
180 func (r *binaryReaderReaderAt) Bytes(b []byte, n, off int64) ([]byte, error) {
181 if n == 0 {
182 return nil, nil
183 } else if b == nil {
184 b = make([]byte, n)
185 }
186 if m, err := r.r.ReadAt(b, off); err != nil {
187 return b[:m], err
188 } else if int64(m) != n {
189 return b[:m], errors.New("reader: could not read all bytes")
190 }
191 return b, nil
192 }
193
194 type BinaryReader struct {
195 f IBinaryReader
196 pos int64
197 err error
198
199 ByteOrder binary.ByteOrder
200 }
201
202 func NewBinaryReader(f IBinaryReader) *BinaryReader {
203 return &BinaryReader{
204 f: f,
205 ByteOrder: binary.BigEndian,
206 }
207 }
208
209 // Will use Bytes when interface { Bytes() []byte } is implemented (n not used), Seeker when io.Seeker is implemented (negative n tolerated), ReaderAt when io.ReaderAt is implemented, otherwise it will read all bytes if n is negative or returns a non-Seeking/non-ReaderAt reader that does not allow Seek.
210 func NewBinaryReaderReader(r io.Reader, n int64) (*BinaryReader, error) {
211 var f IBinaryReader
212 if z, ok := r.(*BinaryReader); ok {
213 return z, nil
214 } else if b, ok := r.(interface{ Bytes() []byte }); ok {
215 fb := newBinaryReaderBytes(b.Bytes())
216 if closer, ok := r.(io.Closer); ok {
217 fb.closer = closer
218 }
219 f = fb
220 } else if seeker, ok := r.(io.ReadSeeker); ok {
221 // seeker seems faster than readerAt by 10%
222 if n < 0 {
223 if offset, err := seeker.Seek(0, os.SEEK_CUR); err != nil {
224 return nil, err
225 } else if n, err = seeker.Seek(0, os.SEEK_END); err != nil {
226 return nil, err
227 } else if _, err = seeker.Seek(offset, os.SEEK_SET); err != nil {
228 return nil, err
229 }
230 }
231 f = newBinaryReaderSeeker(seeker, n)
232 } else if readerAt, ok := r.(io.ReaderAt); ok && 0 < n {
233 f = newBinaryReaderReaderAt(readerAt, n)
234 } else if n < 0 {
235 b, err := io.ReadAll(r)
236 if err != nil {
237 return nil, err
238 }
239 fb := newBinaryReaderBytes(b)
240 if closer, ok := r.(io.Closer); ok {
241 fb.closer = closer
242 }
243 f = fb
244 } else {
245 f = newBinaryReaderReader(r, n)
246 }
247 return NewBinaryReader(f), nil
248 }
249
250 func NewBinaryReaderBytes(data []byte) *BinaryReader {
251 f := newBinaryReaderBytes(data)
252 return NewBinaryReader(f)
253 }
254
255 func NewBinaryReaderFile(f *os.File) (*BinaryReader, error) {
256 info, err := f.Stat()
257 if err != nil {
258 return nil, err
259 }
260 return NewBinaryReader(newBinaryReaderSeeker(f, info.Size())), nil
261 }
262
263 func NewBinaryReaderPath(filename string) (*BinaryReader, error) {
264 f, err := os.Open(filename)
265 if err != nil {
266 return nil, err
267 }
268 r, err := NewBinaryReaderFile(f)
269 if err != nil {
270 f.Close()
271 return nil, err
272 }
273 return r, nil
274 }
275
276 func (r *BinaryReader) IBinaryReader() IBinaryReader {
277 return r.f
278 }
279
280 func (r *BinaryReader) Clone() *BinaryReader {
281 return &BinaryReader{
282 f: r.f,
283 pos: r.pos,
284 err: r.err,
285 ByteOrder: r.ByteOrder,
286 }
287 }
288
289 func (r *BinaryReader) Err() error {
290 return r.err
291 }
292
293 func (r *BinaryReader) Close() error {
294 if err := r.f.Close(); err != nil {
295 return err
296 }
297 return r.err
298 }
299
300 // InPageCache returns true if the range is already in the page cache (for mmap).
301 func (r *BinaryReader) InPageCache(start, end int64) bool {
302 index := r.Pos() / PageSize
303 return start/PageSize == index && end/PageSize == index
304 }
305
306 // Pos returns the reader's position.
307 func (r *BinaryReader) Pos() int64 {
308 return r.pos
309 }
310
311 // Len returns the remaining length of the buffer.
312 func (r *BinaryReader) Len() int64 {
313 return r.f.Len() - r.pos
314 }
315
316 // Seek complies with io.Seeker.
317 func (r *BinaryReader) Seek(off int64, whence int) (int64, error) {
318 if whence == 0 {
319 if off < 0 || r.f.Len() < off {
320 return 0, fmt.Errorf("invalid offset")
321 }
322 r.pos = off
323 } else if whence == 1 {
324 if r.pos+off < 0 || r.f.Len() < r.pos+off {
325 return 0, fmt.Errorf("invalid offset")
326 }
327 r.pos += off
328 } else if whence == 2 {
329 if off < -r.f.Len() || 0 < off {
330 return 0, fmt.Errorf("invalid offset")
331 }
332 r.pos = r.f.Len() - off
333 } else {
334 return 0, fmt.Errorf("invalid whence")
335 }
336 return r.pos, nil
337 }
338
339 // Read complies with io.Reader.
340 func (r *BinaryReader) Read(b []byte) (int, error) {
341 data, err := r.f.Bytes(b, int64(len(b)), r.pos)
342 r.pos += int64(len(data))
343 return len(data), err
344 }
345
346 // ReadAt complies with io.ReaderAt.
347 func (r *BinaryReader) ReadAt(b []byte, off int64) (int, error) {
348 data, err := r.f.Bytes(b, int64(len(b)), off)
349 return len(data), err
350 }
351
352 // ReadBytes reads n bytes.
353 func (r *BinaryReader) ReadBytes(n int64) []byte {
354 data, err := r.f.Bytes(nil, n, r.pos)
355 r.pos += int64(len(data))
356 if r.err == nil {
357 r.err = err
358 }
359 return data
360 }
361
362 // ReadString reads a string of length n.
363 func (r *BinaryReader) ReadString(n int64) string {
364 return string(r.ReadBytes(n))
365 }
366
367 // ReadByte reads a single byte.
368 func (r *BinaryReader) ReadByte() (byte, error) {
369 data := r.ReadBytes(1)
370 if data == nil {
371 return 0, r.err
372 }
373 return data[0], nil
374 }
375
376 // ReadUint8 reads a uint8.
377 func (r *BinaryReader) ReadUint8() uint8 {
378 data := r.ReadBytes(1)
379 if data == nil {
380 return 0
381 }
382 return data[0]
383 }
384
385 // ReadUint16 reads a uint16.
386 func (r *BinaryReader) ReadUint16() uint16 {
387 data := r.ReadBytes(2)
388 if data == nil {
389 return 0
390 } else if r.ByteOrder == binary.LittleEndian {
391 return uint16(data[1])<<8 | uint16(data[0])
392 }
393 return uint16(data[0])<<8 | uint16(data[1])
394 }
395
396 // ReadUint24 reads a uint24 into a uint32.
397 func (r *BinaryReader) ReadUint24() uint32 {
398 b := r.ReadBytes(3)
399 if b == nil {
400 return 0
401 } else if r.ByteOrder == binary.LittleEndian {
402 return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16
403 } else {
404 return uint32(b[2]) | uint32(b[1])<<8 | uint32(b[0])<<16
405 }
406 }
407
408 // ReadUint32 reads a uint32.
409 func (r *BinaryReader) ReadUint32() uint32 {
410 data := r.ReadBytes(4)
411 if data == nil {
412 return 0
413 } else if r.ByteOrder == binary.LittleEndian {
414 return uint32(data[3])<<24 | uint32(data[2])<<16 | uint32(data[1])<<8 | uint32(data[0])
415 }
416 return uint32(data[0])<<24 | uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3])
417 }
418
419 // ReadUint64 reads a uint64.
420 func (r *BinaryReader) ReadUint64() uint64 {
421 data := r.ReadBytes(8)
422 if data == nil {
423 return 0
424 } else if r.ByteOrder == binary.LittleEndian {
425 return uint64(data[7])<<56 | uint64(data[6])<<48 | uint64(data[5])<<40 | uint64(data[4])<<32 | uint64(data[3])<<24 | uint64(data[2])<<16 | uint64(data[1])<<8 | uint64(data[0])
426 }
427 return uint64(data[0])<<56 | uint64(data[1])<<48 | uint64(data[2])<<40 | uint64(data[3])<<32 | uint64(data[4])<<24 | uint64(data[5])<<16 | uint64(data[6])<<8 | uint64(data[7])
428 }
429
430 // ReadInt8 reads a int8.
431 func (r *BinaryReader) ReadInt8() int8 {
432 return int8(r.ReadUint8())
433 }
434
435 // ReadInt16 reads a int16.
436 func (r *BinaryReader) ReadInt16() int16 {
437 return int16(r.ReadUint16())
438 }
439
440 // ReadInt24 reads a int24 into an int32.
441 func (r *BinaryReader) ReadInt24() int32 {
442 return int32(r.ReadUint24())
443 }
444
445 // ReadInt32 reads a int32.
446 func (r *BinaryReader) ReadInt32() int32 {
447 return int32(r.ReadUint32())
448 }
449
450 // ReadInt64 reads a int64.
451 func (r *BinaryReader) ReadInt64() int64 {
452 return int64(r.ReadUint64())
453 }
454
455 // BinaryWriter is a big endian binary file format writer.
456 type BinaryWriter struct {
457 buf []byte
458 ByteOrder binary.AppendByteOrder
459 }
460
461 // NewBinaryWriter returns a big endian binary file format writer.
462 func NewBinaryWriter(buf []byte) *BinaryWriter {
463 return &BinaryWriter{
464 buf: buf,
465 ByteOrder: binary.BigEndian,
466 }
467 }
468
469 // Len returns the buffer's length in bytes.
470 func (w *BinaryWriter) Len() int64 {
471 return int64(len(w.buf))
472 }
473
474 // Bytes returns the buffer's bytes.
475 func (w *BinaryWriter) Bytes() []byte {
476 return w.buf
477 }
478
479 // Write complies with io.Writer.
480 func (w *BinaryWriter) Write(b []byte) (int, error) {
481 w.buf = append(w.buf, b...)
482 return len(b), nil
483 }
484
485 // WriteBytes writes the given bytes to the buffer.
486 func (w *BinaryWriter) WriteBytes(v []byte) {
487 w.buf = append(w.buf, v...)
488 }
489
490 // WriteString writes the given string to the buffer.
491 func (w *BinaryWriter) WriteString(v string) {
492 w.WriteBytes([]byte(v))
493 }
494
495 // WriteByte writes the given byte to the buffer.
496 func (w *BinaryWriter) WriteByte(v byte) {
497 w.WriteBytes([]byte{v})
498 }
499
500 // WriteUint8 writes the given uint8 to the buffer.
501 func (w *BinaryWriter) WriteUint8(v uint8) {
502 w.WriteByte(v)
503 }
504
505 // WriteUint16 writes the given uint16 to the buffer.
506 func (w *BinaryWriter) WriteUint16(v uint16) {
507 w.buf = w.ByteOrder.AppendUint16(w.buf, v)
508 }
509
510 // WriteUint24 writes the given uint32 as a uint24 to the buffer.
511 func (w *BinaryWriter) WriteUint24(v uint32) {
512 if w.ByteOrder == binary.LittleEndian {
513 w.buf = append(w.buf, byte(v), byte(v>>8), byte(v>>16))
514 } else {
515 w.buf = append(w.buf, byte(v>>16), byte(v>>8), byte(v))
516 }
517 }
518
519 // WriteUint32 writes the given uint32 to the buffer.
520 func (w *BinaryWriter) WriteUint32(v uint32) {
521 w.buf = w.ByteOrder.AppendUint32(w.buf, v)
522 }
523
524 // WriteUint64 writes the given uint64 to the buffer.
525 func (w *BinaryWriter) WriteUint64(v uint64) {
526 w.buf = w.ByteOrder.AppendUint64(w.buf, v)
527 }
528
529 // WriteInt8 writes the given int8 to the buffer.
530 func (w *BinaryWriter) WriteInt8(v int8) {
531 w.WriteUint8(uint8(v))
532 }
533
534 // WriteInt16 writes the given int16 to the buffer.
535 func (w *BinaryWriter) WriteInt16(v int16) {
536 w.WriteUint16(uint16(v))
537 }
538
539 // WriteInt24 writes the given int32 as an in24 to the buffer.
540 func (w *BinaryWriter) WriteInt24(v int32) {
541 w.WriteUint24(uint32(v))
542 }
543
544 // WriteInt32 writes the given int32 to the buffer.
545 func (w *BinaryWriter) WriteInt32(v int32) {
546 w.WriteUint32(uint32(v))
547 }
548
549 // WriteInt64 writes the given int64 to the buffer.
550 func (w *BinaryWriter) WriteInt64(v int64) {
551 w.WriteUint64(uint64(v))
552 }
553
554 // BitmapReader is a binary bitmap reader.
555 type BitmapReader struct {
556 buf []byte
557 pos uint32 // TODO: to uint64
558 eof bool
559 }
560
561 // NewBitmapReader returns a binary bitmap reader.
562 func NewBitmapReader(buf []byte) *BitmapReader {
563 return &BitmapReader{buf, 0, false}
564 }
565
566 // Pos returns the current bit position.
567 func (r *BitmapReader) Pos() uint32 {
568 return r.pos
569 }
570
571 // EOF returns if we reached the buffer's end-of-file.
572 func (r *BitmapReader) EOF() bool {
573 return r.eof
574 }
575
576 // Read reads the next bit.
577 func (r *BitmapReader) Read() bool {
578 if r.eof || uint32(len(r.buf)) <= (r.pos+1)/8 {
579 r.eof = true
580 return false
581 }
582 bit := r.buf[r.pos>>3]&(0x80>>(r.pos&7)) != 0
583 r.pos += 1
584 return bit
585 }
586
587 // BitmapWriter is a binary bitmap writer.
588 type BitmapWriter struct {
589 buf []byte
590 pos uint64
591 }
592
593 // NewBitmapWriter returns a binary bitmap writer.
594 func NewBitmapWriter(buf []byte) *BitmapWriter {
595 return &BitmapWriter{buf, 0}
596 }
597
598 // Len returns the buffer's length in bytes.
599 func (w *BitmapWriter) Len() int64 {
600 return int64(len(w.buf))
601 }
602
603 // Bytes returns the buffer's bytes.
604 func (w *BitmapWriter) Bytes() []byte {
605 return w.buf
606 }
607
608 // Write writes the next bit.
609 func (w *BitmapWriter) Write(bit bool) {
610 if uint64(len(w.buf)) <= (w.pos+1)/8 {
611 w.buf = append(w.buf, 0)
612 }
613 if bit {
614 w.buf[w.pos>>3] = w.buf[w.pos>>3] | (0x80 >> (w.pos & 7))
615 }
616 w.pos += 1
617 }