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
18#[derive(Clone, Copy, Eq, PartialEq)]
20pub enum FixtureBody<'a> {
21 Bytes(&'a [u8]),
23 Repeated {
25 byte: u8,
27 len: usize,
29 },
30}
31
32impl<'a> FixtureBody<'a> {
33 pub const fn new(bytes: &'a [u8]) -> Result<Self, FixtureBodyError> {
35 if bytes.len() > MAX_FIXTURE_BODY_BYTES {
36 return Err(FixtureBodyError::TooLarge);
37 }
38 Ok(Self::Bytes(bytes))
39 }
40
41 pub const fn repeated(byte: u8, len: usize) -> Result<Self, FixtureBodyError> {
43 if len > MAX_FIXTURE_BODY_BYTES {
44 return Err(FixtureBodyError::TooLarge);
45 }
46 Ok(Self::Repeated { byte, len })
47 }
48
49 #[must_use]
51 pub const fn len(self) -> usize {
52 match self {
53 Self::Bytes(bytes) => bytes.len(),
54 Self::Repeated { len, .. } => len,
55 }
56 }
57
58 #[must_use]
60 pub const fn is_empty(self) -> bool {
61 self.len() == 0
62 }
63
64 #[must_use]
66 pub const fn as_bytes(self) -> Option<&'a [u8]> {
67 match self {
68 Self::Bytes(bytes) => Some(bytes),
69 Self::Repeated { .. } => None,
70 }
71 }
72
73 pub fn write_to(self, output: &mut [u8]) -> Result<usize, FixtureBodyError> {
75 let len = self.len();
76 let target = output
77 .get_mut(..len)
78 .ok_or(FixtureBodyError::OutputTooSmall)?;
79 match self {
80 Self::Bytes(bytes) => target.copy_from_slice(bytes),
81 Self::Repeated { byte, .. } => target.fill(byte),
82 }
83 Ok(len)
84 }
85}
86
87impl fmt::Debug for FixtureBody<'_> {
88 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89 formatter
90 .debug_struct("FixtureBody")
91 .field("contents", &"[redacted]")
92 .field("len", &self.len())
93 .finish()
94 }
95}