Skip to main content

dlms_cosem_kit/
codec.rs

1//! The cursor codec: a reader, a writer, and an error that always knows *where*.
2//!
3//! Every decoder in this crate is a function over a [`Reader`] and every encoder a
4//! function over a [`Writer`]. There is no parser-combinator dependency: DLMS encodings
5//! are length-prefixed and tag-dispatched, and a hand-written cursor keeps the byte
6//! offset of a failure exact, which is what a protocol translator prints and what a
7//! fuzz finding is triaged from.
8//!
9//! Neither side can panic. Every read is bounds-checked, every arithmetic operation on
10//! a length is checked, and the only way out of a decoder is a [`Result`].
11
12use core::fmt;
13
14/// What went wrong.
15///
16/// The variants distinguish the cases a caller can act on — a truncated frame may
17/// complete on the next read, an unknown tag never will.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum ErrorKind {
21    /// The input ended inside a value. `needed` is how many more bytes this particular
22    /// read wanted, which is a lower bound on what the whole value needs.
23    Truncated {
24        /// Bytes the failing read still wanted.
25        needed: usize,
26    },
27    /// A tag that is not defined at this position.
28    InvalidTag(u8),
29    /// A value outside the set the specification defines for this field.
30    InvalidValue,
31    /// A well-formed value of the wrong type for the position it appeared in.
32    ///
33    /// Distinct from [`ErrorKind::InvalidValue`] because the caller can act on it
34    /// differently: the bytes decoded, the field is simply not what this position needs —
35    /// a delta whose width disagrees with the column it continues, say. Coercing instead
36    /// would hand back a number nobody sent.
37    TypeMismatch,
38    /// A length prefix that cannot be represented, or that exceeds the remaining input.
39    InvalidLength,
40    /// Nesting deeper than the configured limit. Guards recursion on hostile input.
41    DepthExceeded,
42    /// A value that would take more work to expand than any real one needs.
43    ///
44    /// The sibling of [`ErrorKind::DepthExceeded`]: depth bounds how far a decoder
45    /// recurses, this bounds how *wide* it goes. A compact array's type description
46    /// multiplies — `array 7425 of array 285 of array 257` is fourteen bytes describing
47    /// half a billion values — so the cost of walking one must be bounded before it is
48    /// walked, not discovered while walking it.
49    WorkExceeded,
50    /// The output buffer is full.
51    BufferTooSmall {
52        /// Bytes the failing write still wanted.
53        needed: usize,
54    },
55    /// A frame check sequence, header check sequence or CRC did not match.
56    BadChecksum,
57    /// An authentication tag did not verify, or a signature did not verify.
58    BadTag,
59    /// An invocation counter that has already been accepted, or is too old to prove
60    /// anything about.
61    ///
62    /// Distinct from [`ErrorKind::BadTag`] because the two are different events. A bad
63    /// tag is a forgery or the wrong key; a replay is a message that really was sent
64    /// under the real key, and is most often a retransmission or a peer that restarted
65    /// from a stale counter. The standard has a service error for exactly this —
66    /// `invocation-counter-error`, which carries the value the receiver expects next — and
67    /// a server cannot send it without being able to tell the two apart.
68    Replay,
69    /// The peer's message is well formed but not allowed in this state.
70    UnexpectedMessage,
71    /// A field is longer than this build can represent without `alloc`.
72    Unsupported,
73}
74
75impl fmt::Display for ErrorKind {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::Truncated { needed } => write!(f, "truncated, needed {needed} more byte(s)"),
79            Self::InvalidTag(t) => write!(f, "invalid tag {t:#04x}"),
80            Self::InvalidValue => f.write_str("invalid value"),
81            Self::TypeMismatch => f.write_str("value is not of the type this position requires"),
82            Self::InvalidLength => f.write_str("invalid length"),
83            Self::DepthExceeded => f.write_str("nesting too deep"),
84            Self::WorkExceeded => f.write_str("a value that would take unbounded work to expand"),
85            Self::BufferTooSmall { needed } => write!(f, "buffer too small, needed {needed}"),
86            Self::BadChecksum => f.write_str("checksum mismatch"),
87            Self::BadTag => f.write_str("authentication tag mismatch"),
88            Self::Replay => f.write_str("invocation counter already accepted, or too old"),
89            Self::UnexpectedMessage => f.write_str("message not allowed in this state"),
90            Self::Unsupported => f.write_str("not supported in this build"),
91        }
92    }
93}
94
95/// An error and the byte offset it happened at.
96///
97/// The offset is into the buffer the failing [`Reader`] or [`Writer`] was given, so a
98/// translator can print `byte 47: invalid tag 0x1b` without threading positions through
99/// the call stack by hand.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct Error {
102    /// What went wrong.
103    pub kind: ErrorKind,
104    /// Where, as an offset from the start of the buffer.
105    pub offset: usize,
106}
107
108impl Error {
109    /// Construct an error at `offset`.
110    #[must_use]
111    pub const fn new(kind: ErrorKind, offset: usize) -> Self {
112        Self { kind, offset }
113    }
114
115    /// True when more input might complete this value.
116    ///
117    /// A stream transport uses this to decide between "wait for more bytes" and
118    /// "this frame is broken, resynchronise".
119    #[must_use]
120    pub const fn is_truncated(&self) -> bool {
121        matches!(self.kind, ErrorKind::Truncated { .. })
122    }
123}
124
125impl fmt::Display for Error {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        write!(f, "byte {}: {}", self.offset, self.kind)
128    }
129}
130
131#[cfg(feature = "std")]
132impl std::error::Error for Error {}
133
134/// The crate's result type.
135pub type Result<T> = core::result::Result<T, Error>;
136
137/// A bounds-checked cursor over borrowed input.
138///
139/// Every method that fails leaves the position untouched, so a caller that hits
140/// [`ErrorKind::Truncated`] can retry the same read after more bytes arrive.
141#[derive(Debug, Clone)]
142pub struct Reader<'a> {
143    buf: &'a [u8],
144    pos: usize,
145    base: usize,
146}
147
148impl<'a> Reader<'a> {
149    /// A reader over `buf`, with offsets reported from its start.
150    #[must_use]
151    pub const fn new(buf: &'a [u8]) -> Self {
152        Self { buf, pos: 0, base: 0 }
153    }
154
155    /// A reader over `buf` whose reported offsets are shifted by `base`.
156    ///
157    /// Used when a sub-decoder is handed a slice out of a larger frame and its errors
158    /// should still point at the position in that frame.
159    #[must_use]
160    pub const fn with_base(buf: &'a [u8], base: usize) -> Self {
161        Self { buf, pos: 0, base }
162    }
163
164    /// Bytes not yet consumed.
165    #[must_use]
166    pub const fn remaining(&self) -> usize {
167        self.buf.len().saturating_sub(self.pos)
168    }
169
170    /// True when every byte has been consumed.
171    #[must_use]
172    pub const fn is_empty(&self) -> bool {
173        self.remaining() == 0
174    }
175
176    /// The current offset, including the base.
177    ///
178    /// Saturating rather than wrapping: this is a byte position for a diagnostic, and
179    /// the sum cannot overflow for any buffer that exists. Writing it as a plain `+`
180    /// still emitted an overflow check, and because [`Reader::err`] calls this, that
181    /// single addition put a panic path in every decoder in the crate.
182    #[must_use]
183    pub const fn offset(&self) -> usize {
184        self.base.saturating_add(self.pos)
185    }
186
187    /// The bytes not yet consumed, without consuming them.
188    #[must_use]
189    pub fn rest(&self) -> &'a [u8] {
190        self.buf.get(self.pos..).unwrap_or(&[])
191    }
192
193    /// How many bytes this reader has taken, ignoring the base.
194    ///
195    /// This is what a *probe* reader is for: make one over `rest()`, run a sub-decoder,
196    /// ask how much it used. A list finds its end that way, and so does a compact array's
197    /// type description.
198    ///
199    /// Written `probe.offset() - base` instead, that is a subtraction the optimiser
200    /// cannot discharge — it cannot see that a reader's offset never goes below its own
201    /// base — so it emits an overflow check in *every monomorphisation* of every such
202    /// decoder. Asking the reader needs no arithmetic at all.
203    #[must_use]
204    pub const fn consumed(&self) -> usize {
205        self.pos
206    }
207
208    /// An error at the current position.
209    #[must_use]
210    pub const fn err(&self, kind: ErrorKind) -> Error {
211        Error::new(kind, self.offset())
212    }
213
214    /// An error at `offset` bytes before the current position.
215    #[must_use]
216    pub const fn err_back(&self, kind: ErrorKind, back: usize) -> Error {
217        Error::new(kind, self.offset().saturating_sub(back))
218    }
219
220    /// Fail unless at least `n` bytes remain.
221    pub fn ensure(&self, n: usize) -> Result<()> {
222        if self.remaining() < n {
223            return Err(self.err(ErrorKind::Truncated { needed: n - self.remaining() }));
224        }
225        Ok(())
226    }
227
228    /// Take exactly `n` bytes.
229    pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
230        self.ensure(n)?;
231        // `ensure` has established that this fits, but the slice is taken with `get` so
232        // the bound is discharged by the type rather than left to the optimiser to
233        // rediscover. This is the primitive every decoder in the crate reads through,
234        // so a bounds check that survives here is a panic path in all of them.
235        let end = self.pos.checked_add(n).ok_or_else(|| self.err(ErrorKind::InvalidLength))?;
236        let out = self.buf.get(self.pos..end).ok_or_else(|| self.err(ErrorKind::InvalidLength))?;
237        self.pos = end;
238        Ok(out)
239    }
240
241    /// Take the remaining bytes.
242    pub fn take_rest(&mut self) -> &'a [u8] {
243        let out = self.rest();
244        self.pos = self.buf.len();
245        out
246    }
247
248    /// Take exactly `N` bytes as an array.
249    pub fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
250        let s = self.take(N)?;
251        let mut out = [0u8; N];
252        out.copy_from_slice(s);
253        Ok(out)
254    }
255
256    /// One byte.
257    pub fn u8(&mut self) -> Result<u8> {
258        let b = *self.buf.get(self.pos).ok_or_else(|| self.err(ErrorKind::Truncated { needed: 1 }))?;
259        self.pos = self.pos.saturating_add(1);
260        Ok(b)
261    }
262
263    /// One byte, without consuming it.
264    pub fn peek_u8(&self) -> Result<u8> {
265        self.buf.get(self.pos).copied().ok_or_else(|| self.err(ErrorKind::Truncated { needed: 1 }))
266    }
267
268    /// A big-endian `u16`. DLMS is big-endian throughout.
269    pub fn u16(&mut self) -> Result<u16> {
270        Ok(u16::from_be_bytes(self.array()?))
271    }
272
273    /// A big-endian `u32`.
274    pub fn u32(&mut self) -> Result<u32> {
275        Ok(u32::from_be_bytes(self.array()?))
276    }
277
278    /// A big-endian `u64`.
279    pub fn u64(&mut self) -> Result<u64> {
280        Ok(u64::from_be_bytes(self.array()?))
281    }
282
283    /// A big-endian `i8`, `i16`, `i32`, `i64` — sign is the only difference.
284    pub fn i8(&mut self) -> Result<i8> {
285        Ok(self.u8()? as i8)
286    }
287
288    /// A big-endian `i16`.
289    pub fn i16(&mut self) -> Result<i16> {
290        Ok(self.u16()? as i16)
291    }
292
293    /// A big-endian `i32`.
294    pub fn i32(&mut self) -> Result<i32> {
295        Ok(self.u32()? as i32)
296    }
297
298    /// A big-endian `i64`.
299    pub fn i64(&mut self) -> Result<i64> {
300        Ok(self.u64()? as i64)
301    }
302
303    /// Skip `n` bytes.
304    pub fn skip(&mut self, n: usize) -> Result<()> {
305        self.take(n).map(|_| ())
306    }
307
308    /// An A-XDR length: a short form below `0x80`, else `0x80 | n` and `n` big-endian
309    /// bytes. `n` above four, and the indefinite form `0x80`, are refused — DLMS uses
310    /// neither and accepting them widens the attack surface for nothing.
311    pub fn length(&mut self) -> Result<usize> {
312        let first = self.u8()?;
313        if first < 0x80 {
314            return Ok(usize::from(first));
315        }
316        let n = usize::from(first & 0x7f);
317        if n == 0 || n > 4 {
318            return Err(self.err_back(ErrorKind::InvalidLength, 1));
319        }
320        let bytes = self.take(n)?;
321        let mut v: u64 = 0;
322        for b in bytes {
323            v = (v << 8) | u64::from(*b);
324        }
325        usize::try_from(v).map_err(|_| self.err_back(ErrorKind::InvalidLength, n))
326    }
327
328    /// A length followed by that many bytes.
329    pub fn length_prefixed(&mut self) -> Result<&'a [u8]> {
330        let n = self.length()?;
331        self.take(n)
332    }
333
334    /// Run `f` over the next `n` bytes in a reader of their own, and require it to
335    /// consume all of them.
336    ///
337    /// This is how a nested structure is decoded without letting the inner decoder read
338    /// past its own field — the single most common way a protocol parser is made to
339    /// read out of bounds elsewhere in the frame.
340    pub fn nested<T>(&mut self, n: usize, f: impl FnOnce(&mut Reader<'a>) -> Result<T>) -> Result<T> {
341        let base = self.offset();
342        let bytes = self.take(n)?;
343        let mut inner = Reader::with_base(bytes, base);
344        let out = f(&mut inner)?;
345        if !inner.is_empty() {
346            return Err(inner.err(ErrorKind::InvalidLength));
347        }
348        Ok(out)
349    }
350}
351
352/// A sink for encoded bytes.
353///
354/// Implemented for a caller-owned slice ([`SliceWriter`]), for `alloc::vec::Vec<u8>` and
355/// for `heapless::Vec`, so the same encoder serves a microcontroller with a static
356/// buffer and a head-end that grows one.
357pub trait Writer {
358    /// Append `bytes`.
359    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()>;
360
361    /// How many bytes have been written so far, for error offsets and for sizing a
362    /// length prefix against a [`CountingWriter`].
363    fn written(&self) -> usize;
364
365    /// Append one byte.
366    fn write_u8(&mut self, b: u8) -> Result<()> {
367        self.write_bytes(&[b])
368    }
369
370    /// Append a big-endian `u16`.
371    fn write_u16(&mut self, v: u16) -> Result<()> {
372        self.write_bytes(&v.to_be_bytes())
373    }
374
375    /// Append a big-endian `u32`.
376    fn write_u32(&mut self, v: u32) -> Result<()> {
377        self.write_bytes(&v.to_be_bytes())
378    }
379
380    /// Append a big-endian `u64`.
381    fn write_u64(&mut self, v: u64) -> Result<()> {
382        self.write_bytes(&v.to_be_bytes())
383    }
384
385    /// Append an A-XDR length.
386    fn write_length(&mut self, len: usize) -> Result<()> {
387        if len < 0x80 {
388            return self.write_u8(len as u8);
389        }
390        let be = (len as u64).to_be_bytes();
391        let first = be.iter().position(|b| *b != 0).unwrap_or(7);
392        let n = 8 - first;
393        if n > 4 {
394            return Err(Error::new(ErrorKind::InvalidLength, self.written()));
395        }
396        self.write_u8(0x80 | n as u8)?;
397        self.write_bytes(&be[first..])
398    }
399
400    /// Append a length followed by `bytes`.
401    fn write_length_prefixed(&mut self, bytes: &[u8]) -> Result<()> {
402        self.write_length(bytes.len())?;
403        self.write_bytes(bytes)
404    }
405}
406
407/// A [`Writer`] over a caller-owned slice. Never allocates.
408#[derive(Debug)]
409pub struct SliceWriter<'a> {
410    buf: &'a mut [u8],
411    pos: usize,
412}
413
414impl<'a> SliceWriter<'a> {
415    /// A writer that fills `buf` from the start.
416    #[must_use]
417    pub fn new(buf: &'a mut [u8]) -> Self {
418        Self { buf, pos: 0 }
419    }
420
421    /// The bytes written so far.
422    #[must_use]
423    pub fn finish(self) -> &'a mut [u8] {
424        let n = self.pos.min(self.buf.len());
425        &mut self.buf[..n]
426    }
427
428    /// The bytes written so far, borrowed.
429    #[must_use]
430    pub fn as_slice(&self) -> &[u8] {
431        self.buf.get(..self.pos).unwrap_or(self.buf)
432    }
433
434    /// Discard everything written after `at`.
435    ///
436    /// For an encoder that starts a value and then learns it cannot finish it — a store
437    /// that writes half an attribute and then reports a hardware fault, say. Without
438    /// this, the half-written bytes stay in the buffer in front of the error that
439    /// replaces them, and the result is a response whose length agrees with nothing.
440    ///
441    /// Only ever shrinks: `at` beyond what has been written is refused rather than
442    /// treated as an extension into whatever the buffer happened to contain.
443    ///
444    /// # Errors
445    /// [`ErrorKind::InvalidLength`] when `at` is past the current position.
446    pub fn truncate(&mut self, at: usize) -> Result<()> {
447        if at > self.pos {
448            return Err(Error::new(ErrorKind::InvalidLength, self.pos));
449        }
450        self.pos = at;
451        Ok(())
452    }
453}
454
455impl Writer for SliceWriter<'_> {
456    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
457        let end = self.pos.saturating_add(bytes.len());
458        let Some(slot) = self.buf.get_mut(self.pos..end) else {
459            let needed = end.saturating_sub(self.buf.len());
460            return Err(Error::new(ErrorKind::BufferTooSmall { needed }, self.pos));
461        };
462        slot.copy_from_slice(bytes);
463        self.pos = end;
464        Ok(())
465    }
466
467    fn written(&self) -> usize {
468        self.pos
469    }
470}
471
472#[cfg(feature = "alloc")]
473impl Writer for alloc::vec::Vec<u8> {
474    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
475        self.extend_from_slice(bytes);
476        Ok(())
477    }
478
479    fn written(&self) -> usize {
480        self.len()
481    }
482}
483
484#[cfg(feature = "heapless")]
485impl<const N: usize> Writer for heapless::Vec<u8, N> {
486    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
487        self.extend_from_slice(bytes).map_err(|()| {
488            Error::new(ErrorKind::BufferTooSmall { needed: bytes.len() - (N - self.len()) }, self.len())
489        })
490    }
491
492    fn written(&self) -> usize {
493        self.len()
494    }
495}
496
497/// Something that can be written to a [`Writer`].
498pub trait Encode {
499    /// Append the encoding of `self`.
500    fn encode(&self, w: &mut dyn Writer) -> Result<()>;
501
502    /// The number of bytes [`Encode::encode`] will write.
503    ///
504    /// Implementations must agree with `encode`. The default counts what `encode`
505    /// writes, so it agrees by construction; an override that does not is a buffer
506    /// sized wrongly, and `tests/robustness.rs` checks the two against each other for
507    /// everything it decodes.
508    fn encoded_len(&self) -> usize {
509        let mut c = CountingWriter::default();
510        let _ = self.encode(&mut c);
511        c.written()
512    }
513}
514
515/// Something that can be read from a [`Reader`].
516pub trait Decode<'a>: Sized {
517    /// Consume one value.
518    fn decode(r: &mut Reader<'a>) -> Result<Self>;
519
520    /// Consume one value from `bytes`, requiring all of them to be used.
521    fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
522        let mut r = Reader::new(bytes);
523        let v = Self::decode(&mut r)?;
524        if !r.is_empty() {
525            return Err(r.err(ErrorKind::InvalidLength));
526        }
527        Ok(v)
528    }
529}
530
531/// A [`Writer`] that counts instead of storing. Backs [`Encode::encoded_len`].
532#[derive(Debug, Default, Clone, Copy)]
533pub struct CountingWriter {
534    n: usize,
535}
536
537impl CountingWriter {
538    /// The count.
539    #[must_use]
540    pub const fn count(&self) -> usize {
541        self.n
542    }
543}
544
545impl Writer for CountingWriter {
546    fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
547        // Saturating: this counter measures a length nobody has room to reach, and a
548        // plain `+=` here is an overflow check in every `encoded_len` in the crate.
549        self.n = self.n.saturating_add(bytes.len());
550        Ok(())
551    }
552
553    fn written(&self) -> usize {
554        self.n
555    }
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561
562    #[test]
563    fn short_and_long_lengths_round_trip() {
564        for len in [0usize, 1, 0x7f, 0x80, 0xff, 0x100, 0xffff, 0x1_0000, 0x00ff_ffff] {
565            let mut buf = [0u8; 8];
566            let mut w = SliceWriter::new(&mut buf);
567            w.write_length(len).unwrap();
568            let n = w.written();
569            let mut r = Reader::new(&buf[..n]);
570            assert_eq!(r.length().unwrap(), len, "length {len}");
571            assert!(r.is_empty());
572        }
573    }
574
575    #[test]
576    fn length_form_is_the_shortest_one() {
577        let mut buf = [0u8; 8];
578        let mut w = SliceWriter::new(&mut buf);
579        w.write_length(0x7f).unwrap();
580        assert_eq!(w.as_slice(), [0x7f]);
581        let mut w = SliceWriter::new(&mut buf);
582        w.write_length(0x80).unwrap();
583        assert_eq!(w.as_slice(), [0x81, 0x80]);
584        let mut w = SliceWriter::new(&mut buf);
585        w.write_length(0x1234).unwrap();
586        assert_eq!(w.as_slice(), [0x82, 0x12, 0x34]);
587    }
588
589    #[test]
590    fn indefinite_and_oversized_lengths_are_refused() {
591        assert_eq!(Reader::new(&[0x80]).length().unwrap_err().kind, ErrorKind::InvalidLength);
592        assert_eq!(Reader::new(&[0x85, 1, 2, 3, 4, 5]).length().unwrap_err().kind, ErrorKind::InvalidLength);
593    }
594
595    #[test]
596    fn truncation_reports_what_it_needed_and_where() {
597        let mut r = Reader::new(&[0x01, 0x02]);
598        r.u8().unwrap();
599        let e = r.u32().unwrap_err();
600        assert_eq!(e.kind, ErrorKind::Truncated { needed: 3 });
601        assert_eq!(e.offset, 1);
602        assert!(e.is_truncated());
603    }
604
605    #[test]
606    fn a_failed_read_does_not_move_the_cursor() {
607        let mut r = Reader::new(&[0xaa]);
608        assert!(r.u16().is_err());
609        assert_eq!(r.offset(), 0);
610        assert_eq!(r.u8().unwrap(), 0xaa);
611    }
612
613    #[test]
614    fn nested_readers_report_offsets_in_the_outer_frame() {
615        let frame = [0xff, 0xff, 0x00, 0x1b];
616        let mut r = Reader::new(&frame);
617        r.skip(2).unwrap();
618        let e = r
619            .nested(2, |inner| -> Result<()> {
620                inner.u8()?;
621                Err(inner.err(ErrorKind::InvalidTag(0x1b)))
622            })
623            .unwrap_err();
624        assert_eq!(e.offset, 3, "offset is into the outer frame, not the slice");
625    }
626
627    #[test]
628    fn nested_refuses_a_decoder_that_leaves_bytes() {
629        let mut r = Reader::new(&[1, 2, 3, 4]);
630        let e = r.nested(4, |inner| inner.u8()).unwrap_err();
631        assert_eq!(e.kind, ErrorKind::InvalidLength);
632    }
633
634    #[test]
635    fn slice_writer_reports_the_shortfall() {
636        let mut buf = [0u8; 2];
637        let mut w = SliceWriter::new(&mut buf);
638        let e = w.write_bytes(&[1, 2, 3, 4]).unwrap_err();
639        assert_eq!(e.kind, ErrorKind::BufferTooSmall { needed: 2 });
640    }
641
642    #[test]
643    fn truncating_discards_only_what_came_after() {
644        let mut buf = [0u8; 16];
645        let mut w = SliceWriter::new(&mut buf);
646        w.write_bytes(&[1, 2, 3]).unwrap();
647        let mark = w.written();
648        w.write_bytes(&[9, 9, 9, 9]).unwrap();
649        w.truncate(mark).unwrap();
650        assert_eq!(w.as_slice(), [1, 2, 3]);
651        // And writing continues from there, over what was discarded.
652        w.write_bytes(&[4]).unwrap();
653        assert_eq!(w.as_slice(), [1, 2, 3, 4]);
654    }
655
656    #[test]
657    fn truncating_forward_is_refused_rather_than_extending() {
658        // Otherwise it would hand back whatever the caller's buffer happened to hold.
659        let mut buf = [0xAAu8; 16];
660        let mut w = SliceWriter::new(&mut buf);
661        w.write_bytes(&[1, 2]).unwrap();
662        assert_eq!(w.truncate(5).unwrap_err().kind, ErrorKind::InvalidLength);
663        assert_eq!(w.as_slice(), [1, 2], "and leaves the position where it was");
664        assert!(w.truncate(0).is_ok());
665        assert_eq!(w.as_slice(), &[] as &[u8]);
666    }
667
668    #[test]
669    fn counting_writer_agrees_with_a_real_one() {
670        let mut buf = [0u8; 16];
671        let mut w = SliceWriter::new(&mut buf);
672        w.write_length_prefixed(&[1, 2, 3]).unwrap();
673        let mut c = CountingWriter::default();
674        c.write_length_prefixed(&[1, 2, 3]).unwrap();
675        assert_eq!(c.count(), w.written());
676    }
677}