byte_slice/lib.rs
1// +-----------------------------------------------------------------------------------------------+
2// | Copyright 2016 Sean Kerr |
3// | |
4// | Licensed under the Apache License, Version 2.0 (the "License"); |
5// | you may not use this file except in compliance with the License. |
6// | You may obtain a copy of the License at |
7// | |
8// | http://www.apache.org/licenses/LICENSE-2.0 |
9// | |
10// | Unless required by applicable law or agreed to in writing, software |
11// | distributed under the License is distributed on an "AS IS" BASIS, |
12// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13// | See the License for the specific language governing permissions and |
14// | limitations under the License. |
15// +-----------------------------------------------------------------------------------------------+
16// | Author: Sean Kerr <sean@metatomic.io> |
17// +-----------------------------------------------------------------------------------------------+
18
19#[macro_use]
20pub mod macros;
21
22#[cfg(test)]
23mod test;
24
25use std::fmt;
26
27/// Default byte stream type.
28///
29/// All stream macros will accept any struct given as `$context`, as long as they contain the
30/// following four fields:
31///
32/// - `byte` (u8) The most recent byte.
33/// - `mark_index` (usize) Starting index of a collection of marked bytes.
34/// - `stream` (&[u8]) Stream of bytes.
35/// - `stream_index` (usize) Current stream index.
36pub struct ByteStream<'a> {
37 /// Current byte.
38 pub byte: u8,
39
40 /// Mark index.
41 pub mark_index: usize,
42
43 /// Stream data.
44 pub stream: &'a [u8],
45
46 /// Stream index.
47 pub stream_index: usize
48}
49
50impl<'a> ByteStream<'a> {
51 /// Create a new `ByteStream`.
52 pub fn new(stream: &'a [u8]) -> ByteStream<'a> {
53 ByteStream{
54 byte: 0,
55 mark_index: 0,
56 stream: stream,
57 stream_index: 0
58 }
59 }
60}
61
62impl<'a> fmt::Debug for ByteStream<'a> {
63 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
64 if is_visible_8bit!(self.byte) || self.byte == 0x20 || self.byte == 0xFF {
65 write!(formatter, "ByteStream(byte[{}]='{}', mark_index={}, stream_index={})",
66 self.byte, self.byte as char, self.mark_index, self.stream_index)
67 } else {
68 write!(formatter, "ByteStream(byte[{}]='', mark_index={}, stream_index={})",
69 self.byte, self.mark_index, self.stream_index)
70 }
71 }
72}
73
74impl<'a> fmt::Display for ByteStream<'a> {
75 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
76 if is_visible_8bit!(self.byte) || self.byte == 0x20 || self.byte == 0xFF {
77 write!(formatter, "byte[{}]='{}', mark_index={}, stream_index={}",
78 self.byte, self.byte as char, self.mark_index, self.stream_index)
79 } else {
80 write!(formatter, "byte[{}]='', mark_index={}, stream_index={}",
81 self.byte, self.mark_index, self.stream_index)
82 }
83 }
84}