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
//! basic serializers
use crate::internal::*;
use crate::lib::std::io::Write;

macro_rules! try_write(($out:ident, $len:ident, $data:expr) => (
    match $out.write($data) {
        Err(io)           => Err(GenError::IoError(io)),
        Ok(n) if n < $len => Err(GenError::BufferTooSmall($len - n)),
        Ok(_)             => Ok($out)
    }
));

/// Writes a byte slice to the output
///
/// ```rust
/// use cookie_factory::{gen, combinator::slice};
///
/// let mut buf = [0u8; 100];
///
/// {
///   let (buf, pos) = gen(slice(&b"abcd"[..]), &mut buf[..]).unwrap();
///   assert_eq!(pos, 4);
///   assert_eq!(buf.len(), 100 - 4);
/// }
///
/// assert_eq!(&buf[..4], &b"abcd"[..]);
/// ```
pub fn slice<S: AsRef<[u8]>, W: Write>(data: S) -> impl SerializeFn<W> {
    let len = data.as_ref().len();

    move |mut out: WriteContext<W>| try_write!(out, len, data.as_ref())
}

/// Writes a string slice to the output
///
/// ```rust
/// use cookie_factory::{gen, combinator::string};
///
/// let mut buf = [0u8; 100];
///
/// {
///   let (buf, pos) = gen(string("abcd"), &mut buf[..]).unwrap();
///   assert_eq!(pos, 4);
///   assert_eq!(buf.len(), 100 - 4);
/// }
///
/// assert_eq!(&buf[..4], &b"abcd"[..]);
/// ```
pub fn string<S: AsRef<str>, W: Write>(data: S) -> impl SerializeFn<W> {
    let len = data.as_ref().len();

    move |mut out: WriteContext<W>| try_write!(out, len, data.as_ref().as_bytes())
}

/// Writes an hex string to the output
#[cfg(feature = "std")]
/// ```rust
/// use cookie_factory::{gen, combinator::hex};
///
/// let mut buf = [0u8; 100];
///
/// {
///   let (buf, pos) = gen(hex(0x2A), &mut buf[..]).unwrap();
///   assert_eq!(pos, 2);
///   assert_eq!(buf.len(), 100 - 2);
/// }
///
/// assert_eq!(&buf[..2], &b"2A"[..]);
/// ```
pub fn hex<S: crate::lib::std::fmt::UpperHex, W: Write>(data: S) -> impl SerializeFn<W> {
    move |mut out: WriteContext<W>| match write!(out, "{:X}", data) {
        Err(io) => Err(GenError::IoError(io)),
        Ok(()) => Ok(out),
    }
}

/// Skips over some input bytes without writing anything
///
/// ```rust
/// use cookie_factory::{gen, combinator::skip};
///
/// let mut buf = [0u8; 100];
///
/// let (out, pos) = gen(skip(2), &mut buf[..]).unwrap();
///
/// assert_eq!(pos, 2);
/// assert_eq!(out.len(), 98);
/// ```
pub fn skip<W: Write + Skip>(len: usize) -> impl SerializeFn<W> {
    move |out: WriteContext<W>| W::skip(out, len)
}

/// Applies a serializer if the condition is true
///
/// ```rust
/// use cookie_factory::{gen, combinator::{cond, string}};
///
/// let mut buf = [0u8; 100];
///
/// {
///   let (buf, pos) = gen(cond(true, string("abcd")), &mut buf[..]).unwrap();
///   assert_eq!(pos, 4);
///   assert_eq!(buf.len(), 100 - 4);
/// }
///
/// assert_eq!(&buf[..4], &b"abcd"[..]);
/// ```
pub fn cond<F, W: Write>(condition: bool, f: F) -> impl SerializeFn<W>
where
    F: SerializeFn<W>,
{
    move |out: WriteContext<W>| {
        if condition {
            f(out)
        } else {
            Ok(out)
        }
    }
}

/// Reserves space for the `Before` combinator, applies the `Gen` combinator,
/// then applies the `Before` combinator with the output from `Gen` onto the
/// reserved space.
///
/// ```rust
/// use cookie_factory::{gen, gen_simple, sequence::tuple, combinator::{back_to_the_buffer, string}, bytes::be_u8, bytes::be_u32};
///
/// let mut buf = [0; 9];
/// gen_simple(tuple((
///     back_to_the_buffer(
///         4,
///         move |buf| gen(string("test"), buf),
///         move |buf, len| gen_simple(be_u32(len as u32), buf)
///     ),
///     be_u8(42)
/// )), &mut buf[..]).unwrap();
/// assert_eq!(&buf, &[0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, 42]);
/// ```
pub fn back_to_the_buffer<W: BackToTheBuffer, Tmp, Gen, Before>(
    reserved: usize,
    gen: Gen,
    before: Before,
) -> impl SerializeFn<W>
where
    Gen: Fn(WriteContext<W>) -> Result<(WriteContext<W>, Tmp), GenError>,
    Before: Fn(WriteContext<W>, Tmp) -> GenResult<W>,
{
    move |w: WriteContext<W>| W::reserve_write_use(w, reserved, &gen, &before)
}

//missing combinators:
//or
//empty
//then
//stream
//length_value
//text print
//text upperhex
//text lowerhex

#[cfg(test)]
mod test {
    use super::*;
    use crate::bytes::{be_u32, be_u8};
    use crate::sequence::tuple;

    #[test]
    fn test_gen_with_length() {
        let mut buf = [0; 8];
        {
            let (len_buf, buf) = buf.split_at_mut(4);
            let (_, pos) = gen(string("test"), buf).unwrap();
            gen(be_u32(pos as u32), len_buf).unwrap();
        }
        assert_eq!(
            &buf,
            &[0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8]
        );
    }

    #[test]
    fn test_back_to_the_buffer() {
        let mut buf = [0; 9];

        let new_buf = gen_simple(
            tuple((
                back_to_the_buffer(
                    4,
                    move |buf| gen(string("test"), buf),
                    move |buf, len| gen_simple(be_u32(len as u32), buf),
                ),
                be_u8(42),
            )),
            &mut buf[..],
        )
        .unwrap();

        assert!(new_buf.is_empty());
        assert_eq!(
            &buf,
            &[0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, 42]
        );
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_back_to_the_buffer_vec() {
        let buf = Vec::new();

        let buf = gen_simple(
            tuple((
                back_to_the_buffer(
                    4,
                    move |buf| gen(string("test"), buf),
                    move |buf, len| gen_simple(be_u32(len as u32), buf),
                ),
                be_u8(42),
            )),
            buf,
        )
        .unwrap();

        assert_eq!(
            &buf[..],
            &[0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, 42]
        );
    }

    #[test]
    fn test_back_to_the_buffer_cursor() {
        let mut buf = [0; 9];
        {
            let cursor = crate::lib::std::io::Cursor::new(&mut buf[..]);
            let cursor = gen_simple(
                tuple((
                    back_to_the_buffer(
                        4,
                        move |buf| gen(string("test"), buf),
                        move |buf, len| gen_simple(be_u32(len as u32), buf),
                    ),
                    be_u8(42),
                )),
                cursor,
            )
            .unwrap();
            assert_eq!(cursor.position(), 9);
        }
        assert_eq!(
            &buf,
            &[0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, 42]
        );
    }

    #[test]
    fn test_back_to_the_buffer_cursor_counter() {
        let mut buf = [0; 10];
        {
            let cursor = crate::lib::std::io::Cursor::new(&mut buf[..]);
            let (cursor, pos) = gen(
                tuple((
                    be_u8(64),
                    back_to_the_buffer(
                        4,
                        &move |buf| gen(string("test"), buf),
                        &move |buf, len| gen_simple(be_u32(len as u32), buf),
                    ),
                    be_u8(42),
                )),
                cursor,
            )
            .unwrap();
            assert_eq!(pos, 10);
            assert_eq!(cursor.position(), 10);
        }
        assert_eq!(
            &buf,
            &[64, 0, 0, 0, 4, 't' as u8, 'e' as u8, 's' as u8, 't' as u8, 42]
        );
    }
}