source: project/wiki/eggref/4/binary-parse @ 32241

Last change on this file since 32241 was 32241, checked in by felix winkelmann, 6 years ago

removed some call/cc.org links

File size: 2.3 KB
Line 
1[[tags: egg]]
2
3== binary-parse
4
5[[toc:]]
6
7=== Description
8
9Simple parsing of binary data.
10
11=== Author
12
13[[Oleg Kiselyov]]
14
15=== Requirements
16
17None
18
19=== Documentation
20
21If you want bignum support (ie, if the [[numbers]] egg is available), you can use:
22
23  (require-extension big-binary-parse)
24
25Otherwise, the following can be used:
26
27  (require-extension binary-parse)
28
29==== make-bit-reader
30
31<procedure>(make-bit-reader BYTE-READER)</procedure>
32
33Given a {{BYTE-READER}} (a thunk), construct and return a function
34{{(bit-reader N)}} that reads N bits from a byte-stream represented by
35the {{BYTE-READER}}.  The {{BYTE-READER}} is a function that takes no
36arguments and returns the current byte as an exact integer
37{{[0-255]}}. The byte reader should return {{#f}} on EOF.
38
39The bit reader returns N bits as an exact unsigned integer, {{0
40-... (no limit)}}. N must be a positive integer, otherwise the bit
41reader returns {{#f}}. There is no upper limit on N -- other than the
42size of the input stream itself and the amount of (virtual) memory an
43OS is willing to give to your process. If you want to read 1M of
44_bits_, go ahead.
45
46It is assumed that the bit order is the most-significant bit first.
47
48Note the bit reader keeps the following condition true at all times:
49
50  (= current-inport-pos (ceiling (/ no-bits-read 8)))
51
52That is, no byte is read until the very moment we really need (some
53of) its bits. The bit reader does ''not'' "byte read ahead".
54Therefore, it can be used to handle a concatenation of different
55bit/byte streams '''strictly''' sequentially, ''without'' "backing up
56a char", "unreading-char" etc. tricks.
57
58Thus careful attention to byte-buffering and optimization are the
59features of this bit reader.
60
61==== Usage example
62
63<enscript highlight="scheme">
64(use binary-parse)
65
66(define bit-reader (make-bit-reader (lambda () #b11000101)))
67
68(bit-reader 3)
69 => 6
70
71(bit-reader 4)
72 => 2
73</enscript>
74
75==== Notes on the algorithm.
76
77The function recognizes and handles the following special cases:
78
79* The buffer is empty and 8, 16, 24 bits are to be read
80* Reading all bits which are currently in the byte-buffer (and then maybe more)
81* Reading only one bit
82
83=== Changelog
84
85* 1.2 Port to chicken 4
86* 1.1 When [[numbers]] extension is available, a bignum-aware version is additionally built
87* 1.0 Initial release
88
89=== License
90
Note: See TracBrowser for help on using the repository browser.