source: project/wiki/binary-parse @ 8855

Last change on this file since 8855 was 8855, checked in by sjamaan, 12 years ago

See if this triggers a rerender and if that fixes the <example>

File size: 2.4 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=== Download
20
21[[http://www.call-with-current-continuation.org/eggs/binary-parse.egg|binary-parse.egg]]
22
23=== Documentation
24
25If you want bignum support (ie, if the [[numbers]] egg is available), you can use:
26
27  (require-extension big-binary-parse)
28
29Otherwise, the following can be used:
30
31  (require-extension binary-parse)
32
33==== make-bit-reader
34
35<procedure>(make-bit-reader BYTE-READER)</procedure>
36
37Given a {{BYTE-READER}} (a thunk), construct and return a function
38{{(bit-reader N)}} that reads N bits from a byte-stream represented by
39the {{BYTE-READER}}.  The {{BYTE-READER}} is a function that takes no
40arguments and returns the current byte as an exact integer
41{{[0-255]}}. The byte reader should return {{#f}} on EOF.
42
43The bit reader returns N bits as an exact unsigned integer, {{0
44-... (no limit)}}. N must be a positive integer, otherwise the bit
45reader returns {{#f}}. There is no upper limit on N -- other than the
46size of the input stream itself and the amount of (virtual) memory an
47OS is willing to give to your process. If you want to read 1M of
48_bits_, go ahead.
49
50It is assumed that the bit order is the most-significant bit first.
51
52Note the bit reader keeps the following condition true at all times:
53
54  (= current-inport-pos (ceiling (/ no-bits-read 8)))
55
56That is, no byte is read until the very moment we really need (some
57of) its bits. The bit reader does ''not'' "byte read ahead".
58Therefore, it can be used to handle a concatenation of different
59bit/byte streams '''strictly''' sequentially, ''without'' "backing up
60a char", "unreading-char" etc. tricks.
61
62>Thus careful attention to byte-buffering and optimization are the
63features of this bit reader.
64
65==== Usage example
66
67<example>
68<init>(use binary-parse)</init>
69(define bit-reader (make-bit-reader (lambda () #b11000101)))
70<expr>(bit-reader 3)</expr>
71<result>6</result>
72<expr>(bit-reader 4)</expr>
73<result>2</result>
74</example>
75
76==== Notes on the algorithm.
77
78The function recognizes and handles the following special cases:
79
80* The buffer is empty and 8, 16, 24 bits are to be read
81* Reading all bits which are currently in the byte-buffer (and then maybe more)
82* Reading only one bit
83
84=== Changelog
85
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.