diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.toml index 9f641ce..cf4d7bd 100644 --- a/bindings/rust/Cargo.toml +++ b/bindings/rust/Cargo.toml @@ -18,6 +18,8 @@ faster-hex = { version = "^0.6", optional = true } [features] default = ["std"] std = ["bytes/std", "faster-hex"] +# Provide impls for bytes in no_std environment without depending on atomic +bytes_vec = [] [badges] maintenance = { status = "experimental" } diff --git a/bindings/rust/src/bytes.rs b/bindings/rust/src/bytes.rs new file mode 100644 index 0000000..2ca3a55 --- /dev/null +++ b/bindings/rust/src/bytes.rs @@ -0,0 +1,55 @@ +use alloc::{borrow::ToOwned, vec::Vec}; +use core::{ + convert::From, + ops::{Bound, Deref, RangeBounds}, +}; + +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Bytes(Vec); + +impl From> for Bytes { + fn from(value: Vec) -> Self { + Self(value) + } +} + +impl From<&[u8]> for Bytes { + fn from(value: &[u8]) -> Self { + Self(value.to_owned()) + } +} + +impl From for Vec { + fn from(value: Bytes) -> Self { + value.0 + } +} + +impl Deref for Bytes { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Bytes { + pub fn from_static(bytes: &[u8]) -> Self { + Self::from(bytes) + } + + pub fn slice(&self, range: impl RangeBounds) -> Self { + let len = self.len(); + let begin = match range.start_bound() { + Bound::Included(&n) => n, + Bound::Excluded(&n) => n + 1, + Bound::Unbounded => 0, + }; + let end = match range.end_bound() { + Bound::Included(&n) => n + 1, + Bound::Excluded(&n) => n, + Bound::Unbounded => len, + }; + Self::from(&self.0[begin..end]) + } +} diff --git a/bindings/rust/src/lib.rs b/bindings/rust/src/lib.rs index 5576bb3..42eab96 100644 --- a/bindings/rust/src/lib.rs +++ b/bindings/rust/src/lib.rs @@ -9,15 +9,19 @@ cfg_if::cfg_if! { if #[cfg(feature = "std")] { extern crate std; + pub use bytes; pub mod io { pub use std::io::{Error, Result, Write}; } } else { + #[cfg(feature = "bytes_vec")] + pub mod bytes; + #[cfg(not(feature = "bytes_vec"))] + pub use bytes; pub mod io; } } -pub use bytes; pub mod error; pub mod prelude; mod primitive;