o3/buffer/write/consume/
error.rs1use std::num::NonZero;
2
3use crate::buffer::write::spans;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub struct Error {
7 required: NonZero<usize>,
8 available: usize,
9}
10
11impl Error {
12 pub const fn empty(required: NonZero<usize>) -> Self {
14 Self::new(required, 0)
15 }
16
17 pub const fn new(required: NonZero<usize>, room: usize) -> Self {
18 Self {
19 required,
20 available: room,
21 }
22 }
23
24 pub fn check(required: usize, room: usize) -> Result<(), Self> {
25 if required <= room {
26 return Ok(());
27 }
28 Err(Self::new(
29 NonZero::<usize>::MIN.saturating_add(required - 1),
30 room,
31 ))
32 }
33
34 pub const fn into_parts(self) -> (NonZero<usize>, usize) {
35 (self.required, self.available)
36 }
37
38 pub(in crate::buffer) fn checked_end<const N: usize>(
39 start: usize,
40 capacity: usize,
41 slices: &[&[u8]; N],
42 ) -> Result<usize, Self> {
43 Self::check(start, capacity)?;
44 let mut room = capacity - start;
45 for slice in slices {
46 Self::check(slice.len(), room)?;
47 room -= slice.len();
48 }
49 Ok(capacity - room)
50 }
51}
52
53impl From<spans::Gap> for Error {
54 fn from(gap: spans::Gap) -> Self {
55 let (expected, actual) = gap.into_parts();
56 Self::new(
57 NonZero::<usize>::MIN.saturating_add(expected.get() as usize - 1),
58 actual as usize,
59 )
60 }
61}
62
63const _: () = assert!(size_of::<Error>() == 2 * size_of::<usize>());