Skip to content

Commit

Permalink
Add errors for data/text conversions from slices
Browse files Browse the repository at this point in the history
  • Loading branch information
ObsidianMinor committed Oct 13, 2024
1 parent 1d59b62 commit 9b4a5a1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
21 changes: 21 additions & 0 deletions recapn/src/data.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! A fixed size blob of bytes contained in a Cap'n Proto message
use core::fmt;
use core::ops::{Deref, DerefMut};

use crate::internal::Sealed;
Expand All @@ -10,6 +11,18 @@ pub mod ptr {
pub use crate::ptr::{BlobBuilder as Builder, BlobReader as Reader};
}

/// An error returned when trying to set a data field to a slice value if the value is too large.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TryFromSliceError(pub(crate) ());

impl fmt::Display for TryFromSliceError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("attempted to create a data blob from too large a slice")
}
}

impl core::error::Error for TryFromSliceError {}

#[derive(Clone, Copy)]
pub struct Data<T = Family>(T);

Expand Down Expand Up @@ -57,6 +70,14 @@ impl<'a> Reader<'a> {
Self(r)
}

#[inline]
pub const fn try_from_slice(slice: &'a [u8]) -> Result<Self, TryFromSliceError> {
match ptr::Reader::new(slice) {
Some(b) => Ok(Self(b)),
None => Err(TryFromSliceError(())),
}
}

#[inline]
pub const fn len(&self) -> u32 {
self.0.len().get()
Expand Down
12 changes: 12 additions & 0 deletions recapn/src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ macro_rules! text {

const EMPTY_SLICE: &[u8] = &[0];

/// An error returned when trying to set a text field to a string value if the value is too large.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct TryFromStrError(pub(crate) ());

impl fmt::Display for TryFromStrError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("attempted to create a text blob from too large a string")
}
}

impl core::error::Error for TryFromStrError {}

#[derive(Clone, Copy)]
pub struct Text<T = Family>(T);

Expand Down

0 comments on commit 9b4a5a1

Please sign in to comment.