binary-data-schema 0.2.0

Meta language for raw binary serialization
Documentation
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Implementation of the array schema
//!
//! # Length of an Array
//!
//! The length of an array is the number of elements stored.
//!
//! # Parameters
//!
//! | Key           | Type     | Default  | Comment |
//! | ------------- | --------:| --------:| ------- |
//! | `"lengthEncoding"` | `object` | `{ "type": "tillend" }` | The way the length of the string is communicated |
//! | `"minItems"`  |   `uint` | optional | Minimal number of items in the array |
//! | `"maxItems"`  |   `uint` | optional | Maximal number of items in the array |
//! | `"items"`     | data schema | required | Schema validating the elements of the array |
//!
//! ## Validation
//!
//! `"lengthEncoding"` has its own validation rules (see [`LengthEncoding`](crate::LengthEncoding)).
//! This also includes the validity of the values of `"minItems"` and `"maxItems"`.
//!
//! In contrast to JSON schema, BDS does not support [tuples].
//! Accordingly, it is only allowed to have a single data schema as the value of `"items"`.
//!
//! # Features
//!
//! Apart from the length encoding that arrays schemata share with string schemata,
//! there are no special features implemented for array schemata.
//! Neither [tuple validation] nor [uniqueness].
//!
//! [tuples]: https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation
//! [tuple validation]: https://json-schema.org/understanding-json-schema/reference/array.html#tuple-validation
//! [uniqueness]: https://json-schema.org/understanding-json-schema/reference/array.html#uniqueness

use std::{convert::TryFrom, io};

use byteorder::{ReadBytesExt, WriteBytesExt};
use serde::{
    de::{Deserializer, Error as DeError},
    Deserialize,
};
use serde_json::Value;

use crate::{
    integer::{self as int, IntegerSchema},
    util::*,
    DataSchema, Decoder, Encoder, Error, Result,
};

/// Errors validating an [ArraySchema].
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
    #[error("A fixed length array schema requires both 'maxItems' and 'minItems' given and having the same value")]
    IncompleteFixedLength,
    #[error("Patterns and/or paddings must be encodable with the given schema: '{value}' can not be encoded with a {type_} schema: {error}")]
    InvalidPatternOrPadding {
        value: Value,
        type_: &'static str,
        error: Box<Error>,
    },
    #[error("Length encoding 'capacity' requires 'maxItems'")]
    MissingCapacity,
}

/// Errors encoding a string with an [ArraySchema].
#[derive(Debug, thiserror::Error)]
pub enum EncodingError {
    #[error("The value '{value}' can not be encoded with an array schema")]
    InvalidValue { value: String },
    #[error("Writing to buffer failed: {0}")]
    WriteFail(#[from] io::Error),
    #[error("Could not encode length: {0}")]
    EncodingLength(#[from] int::EncodingError),
    #[error("Encoding sub-schema failed: {0}")]
    SubSchema(Box<Error>),
    #[error("{len} elements in array but only a fixed number of {fixed} elements is supported")]
    NotFixedLength { len: usize, fixed: usize },
    #[error("{len} elements in the array but only a length up to {max} elementy can be encoded")]
    ExceedsLengthEncoding { len: usize, max: usize },
    #[error("Array contains the end pattern or the padding {0}")]
    ContainsPatternOrPadding(Value),
    #[error("{len} elements in array but only values up to {cap} elements are valid")]
    ExceedsCapacity { len: usize, cap: usize },
}

impl From<Error> for EncodingError {
    fn from(e: Error) -> Self {
        EncodingError::SubSchema(Box::new(e))
    }
}

/// Errors decoding a string with an [ArraySchema].
#[derive(Debug, thiserror::Error)]
pub enum DecodingError {
    #[error("Reading encoded data failed: {0}")]
    ReadFail(#[from] io::Error),
    #[error("Decoding sub-schema failed: {0}")]
    SubSchema(Box<Error>),
    #[error("Could not deencode length: {0}")]
    DecodingLength(#[from] int::DecodingError),
}

impl From<Error> for DecodingError {
    fn from(e: Error) -> Self {
        DecodingError::SubSchema(Box::new(e))
    }
}

impl DecodingError {
    pub fn due_to_eof(&self) -> bool {
        matches!(self, Self::ReadFail(e) if e.kind() == std::io::ErrorKind::UnexpectedEof)
    }
}

/// How is the length of variable sized data encoded.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawArray {
    #[serde(default)]
    length_encoding: RawLengthEncoding,
    max_items: Option<usize>,
    min_items: Option<usize>,
    items: DataSchema,
}

/// The array schema to describe arrays of homogeneous elements (further information on [the module's documentation](index.html)).
///
/// Contrary to the JSON schema's array schema tuples are not supported.
#[derive(Debug, Clone)]
pub struct ArraySchema {
    pub(crate) length: LengthEncoding<Value>,
    items: DataSchema,
}

fn validate_value(value: &Value, schema: &DataSchema) -> Result<(), ValidationError> {
    let mut buf = Vec::new();
    match schema.encode(&mut buf, value) {
        Ok(_) => Ok(()),
        Err(e) => Err(ValidationError::InvalidPatternOrPadding {
            value: value.clone(),
            type_: schema.type_(),
            error: Box::new(e),
        }),
    }
}

impl TryFrom<RawArray> for ArraySchema {
    type Error = ValidationError;

    fn try_from(raw: RawArray) -> Result<Self, Self::Error> {
        let schema = raw.items;
        let length = match (raw.min_items, raw.max_items) {
            (Some(min), Some(max)) if min == max => Ok(LengthEncoding::Fixed(min)),
            _ => match raw.length_encoding {
                RawLengthEncoding::Fixed => Err(ValidationError::IncompleteFixedLength),
                RawLengthEncoding::ExplicitLength(schema) => {
                    Ok(LengthEncoding::LengthEncoded(schema))
                }
                RawLengthEncoding::EndPattern { sentinel: pattern } => {
                    validate_value(&pattern, &schema)?;
                    Ok(LengthEncoding::EndPattern { sentinel: pattern })
                }
                RawLengthEncoding::Capacity { padding } => {
                    let capacity = raw.max_items.ok_or(ValidationError::MissingCapacity)?;
                    validate_value(&padding, &schema)?;
                    Ok(LengthEncoding::Capacity { padding, capacity })
                }
                RawLengthEncoding::TillEnd => Ok(LengthEncoding::TillEnd),
            },
        }?;

        Ok(Self {
            length,
            items: schema,
        })
    }
}

impl<'de> Deserialize<'de> for ArraySchema {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawArray::deserialize(deserializer)?;
        ArraySchema::try_from(raw).map_err(D::Error::custom)
    }
}

impl ArraySchema {
    pub fn byte_array(length: LengthEncoding<Value>) -> Result<Self, ValidationError> {
        let byte_schema = IntegerSchema::unsigned_byte().into();
        match &length {
            LengthEncoding::EndPattern { sentinel: value }
            | LengthEncoding::Capacity { padding: value, .. } => {
                validate_value(value, &byte_schema)?;
            }
            _ => {}
        }

        Ok(Self {
            length,
            items: byte_schema,
        })
    }
    fn valid_slice(&self, slice: &[Value]) -> Result<(), EncodingError> {
        match &self.length {
            LengthEncoding::Fixed(length) => {
                if slice.len() != *length {
                    Err(EncodingError::NotFixedLength {
                        len: slice.len(),
                        fixed: *length,
                    })
                } else {
                    Ok(())
                }
            }
            LengthEncoding::LengthEncoded(schema) => {
                if schema.max_value() < slice.len() {
                    Err(EncodingError::ExceedsLengthEncoding {
                        len: slice.len(),
                        max: schema.max_value(),
                    })
                } else {
                    Ok(())
                }
            }
            LengthEncoding::EndPattern { sentinel: pattern } => {
                if slice.iter().any(|v| v == pattern) {
                    Err(EncodingError::ContainsPatternOrPadding(pattern.clone()))
                } else {
                    Ok(())
                }
            }
            LengthEncoding::Capacity { padding, capacity } => {
                if *capacity < slice.len() {
                    Err(EncodingError::ExceedsCapacity {
                        len: slice.len(),
                        cap: *capacity,
                    })
                } else if slice.iter().any(|v| v == padding) {
                    Err(EncodingError::ContainsPatternOrPadding(padding.clone()))
                } else {
                    Ok(())
                }
            }
            LengthEncoding::TillEnd => Ok(()),
        }
    }
}

impl Encoder for ArraySchema {
    type Error = EncodingError;

    fn encode<W>(&self, target: &mut W, value: &Value) -> Result<usize, Self::Error>
    where
        W: io::Write + WriteBytesExt,
    {
        let value = value
            .as_array()
            .ok_or_else(|| EncodingError::InvalidValue {
                value: value.to_string(),
            })?;
        let len = value.len();
        self.valid_slice(value)?;

        let mut written = 0;
        // pre-value
        if let LengthEncoding::LengthEncoded(schema) = &self.length {
            let len = len as u64;
            written += schema.encode(target, &(len.into()))?;
        }
        // write array
        for v in value.iter() {
            written += self.items.encode(target, v)?;
        }
        // post-value
        match &self.length {
            LengthEncoding::EndPattern { sentinel } => {
                written += self.items.encode(target, sentinel)?;
            }
            LengthEncoding::Capacity { padding, capacity } => {
                let left = *capacity - len;
                for _ in 0..left {
                    written += self.items.encode(target, padding)?;
                }
            }
            _ => {}
        }

        Ok(written)
    }
}

impl Decoder for ArraySchema {
    type Error = DecodingError;

    fn decode<R>(&self, target: &mut R) -> Result<Value, Self::Error>
    where
        R: io::Read + ReadBytesExt,
    {
        let elements = match &self.length {
            LengthEncoding::Fixed(len) => (0..*len)
                .map(|_| self.items.decode(target))
                .collect::<Result<Vec<_>, _>>()?,
            LengthEncoding::LengthEncoded(schema) => {
                let len = schema
                    .decode(target)?
                    .as_u64()
                    .expect("counts are always unsigned ints");
                (0..len)
                    .map(|_| self.items.decode(target))
                    .collect::<Result<Vec<_>, _>>()?
            }
            LengthEncoding::EndPattern { sentinel: pattern } => {
                let mut elements = Vec::new();
                loop {
                    let element = self.items.decode(target)?;
                    if element != *pattern {
                        elements.push(element);
                    } else {
                        break;
                    }
                }
                elements
            }
            LengthEncoding::Capacity {
                padding: pattern,
                capacity,
            } => {
                let mut elements = Vec::new();
                for _ in 0..*capacity {
                    let element = self.items.decode(target)?;
                    if element != *pattern {
                        elements.push(element);
                    } else {
                        break;
                    }
                }
                elements
            }
            LengthEncoding::TillEnd => {
                let mut elements = Vec::new();
                loop {
                    match self.items.decode(target) {
                        Ok(element) => elements.push(element),
                        Err(e) if e.due_to_eof() => break,
                        Err(e) => return Err(e.into()),
                    }
                }
                elements
            }
        };

        Ok(elements.into())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use anyhow::Result;
    use serde_json::{from_value, json};

    #[test]
    fn default() -> Result<()> {
        let schema = json!({});
        let schema = from_value::<ArraySchema>(schema);
        assert!(schema.is_err());
        Ok(())
    }
    #[test]
    fn schema_only() -> Result<()> {
        let schema = json!({
            "items": {
                "type": "boolean"
            }
        });
        let schema = from_value::<ArraySchema>(schema)?;
        assert!(matches!(
            schema,
            ArraySchema {
                length: LengthEncoding::TillEnd,
                ..
            }
        ));
        Ok(())
    }
    #[test]
    fn fixed() -> Result<()> {
        let schema = json!({
            "minItems": 2,
            "maxItems": 2,
            "items": {
                "type": "boolean"
            }
        });
        let schema = from_value::<ArraySchema>(schema)?;
        assert!(matches!(
            schema,
            ArraySchema {
                length: LengthEncoding::Fixed { .. },
                ..
            }
        ));

        let value = json!([false, true]);
        let mut buffer = vec![];
        assert_eq!(2, schema.encode(&mut buffer, &value)?);
        let expected: [u8; 2] = [0, 1];
        assert_eq!(&expected, buffer.as_slice());

        Ok(())
    }
    #[test]
    fn length() -> Result<()> {
        let schema = json!({
            "lengthEncoding": {
                "@type": "explicitlength",
                "length": 1,
                "signed": false
            },
            "items": {
                "type": "boolean"
            }
        });
        let schema = from_value::<ArraySchema>(schema)?;
        assert!(matches!(
            schema,
            ArraySchema {
                length: LengthEncoding::LengthEncoded(_),
                ..
            }
        ));

        let value = json!([false, true]);
        let mut buffer = vec![];
        assert_eq!(3, schema.encode(&mut buffer, &value)?);
        let expected: [u8; 3] = [2, 0, 1];
        assert_eq!(&expected, buffer.as_slice());

        Ok(())
    }
}