Skip to content

Commit

Permalink
feat: add bytes_vec features
Browse files Browse the repository at this point in the history
  • Loading branch information
quake committed Jan 15, 2024
1 parent 5267456 commit a3f0238
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 3 deletions.
2 changes: 2 additions & 0 deletions bindings/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
55 changes: 55 additions & 0 deletions bindings/rust/src/bytes.rs
Original file line number Diff line number Diff line change
@@ -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<u8>);

impl From<Vec<u8>> for Bytes {
fn from(value: Vec<u8>) -> Self {
Self(value)
}
}

impl From<&[u8]> for Bytes {
fn from(value: &[u8]) -> Self {
Self(value.to_owned())
}
}

impl From<Bytes> for Vec<u8> {
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<usize>) -> 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])
}
}
6 changes: 5 additions & 1 deletion bindings/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions tools/compiler/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a3f0238

Please sign in to comment.