cloud_sdk_testkit/
body.rs1use core::fmt;
4
5pub const MAX_FIXTURE_BODY_BYTES: usize = 8_388_609;
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum FixtureBodyError {
12 TooLarge,
14 OutputTooSmall,
16}
17
18impl_static_error!(FixtureBodyError,
19 Self::TooLarge => "fixture body exceeds the size limit",
20 Self::OutputTooSmall => "fixture output buffer is too small",
21);
22
23#[derive(Clone, Copy, Eq, PartialEq)]
25pub enum FixtureBody<'a> {
26 Bytes(&'a [u8]),
28 Repeated {
30 byte: u8,
32 len: usize,
34 },
35}
36
37impl<'a> FixtureBody<'a> {
38 pub const fn new(bytes: &'a [u8]) -> Result<Self, FixtureBodyError> {
40 if bytes.len() > MAX_FIXTURE_BODY_BYTES {
41 return Err(FixtureBodyError::TooLarge);
42 }
43 Ok(Self::Bytes(bytes))
44 }
45
46 pub const fn repeated(byte: u8, len: usize) -> Result<Self, FixtureBodyError> {
48 if len > MAX_FIXTURE_BODY_BYTES {
49 return Err(FixtureBodyError::TooLarge);
50 }
51 Ok(Self::Repeated { byte, len })
52 }
53
54 #[must_use]
56 pub const fn len(self) -> usize {
57 match self {
58 Self::Bytes(bytes) => bytes.len(),
59 Self::Repeated { len, .. } => len,
60 }
61 }
62
63 #[must_use]
65 pub const fn is_empty(self) -> bool {
66 self.len() == 0
67 }
68
69 #[must_use]
71 pub const fn as_bytes(self) -> Option<&'a [u8]> {
72 match self {
73 Self::Bytes(bytes) => Some(bytes),
74 Self::Repeated { .. } => None,
75 }
76 }
77
78 pub fn write_to(self, output: &mut [u8]) -> Result<usize, FixtureBodyError> {
80 let len = self.len();
81 let target = output
82 .get_mut(..len)
83 .ok_or(FixtureBodyError::OutputTooSmall)?;
84 match self {
85 Self::Bytes(bytes) => target.copy_from_slice(bytes),
86 Self::Repeated { byte, .. } => target.fill(byte),
87 }
88 Ok(len)
89 }
90}
91
92impl fmt::Debug for FixtureBody<'_> {
93 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94 formatter
95 .debug_struct("FixtureBody")
96 .field("contents", &"[redacted]")
97 .field("len", &self.len())
98 .finish()
99 }
100}