Skip to content

Instantly share code, notes, and snippets.

@peterschwarz
Forked from rust-play/playground.rs
Created June 7, 2019 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterschwarz/ab128be50ae1abbac05443869b58518e to your computer and use it in GitHub Desktop.
Save peterschwarz/ab128be50ae1abbac05443869b58518e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::sync::Arc;
use std::ops::Deref;
#[derive(Clone, Debug)]
pub struct BytesRef {
bytes: Arc<Vec<u8>>,
}
impl BytesRef {
pub fn value(&self) -> &[u8] {
&self.bytes
}
}
impl Deref for BytesRef {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl From<Vec<u8>> for BytesRef {
fn from(bytes: Vec<u8>) -> Self {
Self {bytes: Arc::new(bytes)}
}
}
#[derive(Clone, Debug)]
pub struct ImStr {
inner: Arc<Box<str>>
}
impl std::fmt::Display for ImStr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str(&*self.inner)
}
}
impl Deref for ImStr {
type Target = str;
fn deref(&self) -> &Self::Target {
&*self.inner
}
}
impl From<String> for ImStr {
fn from(s: String) -> Self {
Self { inner: Arc::new(s.into_boxed_str()) }
}
}
impl From<&str> for ImStr {
fn from(s: &str) -> Self {
Self { inner: Arc::new(s.to_string().into_boxed_str()) }
}
}
fn main() -> Result<(), i32>{
let mut bytes_ref_1: BytesRef = vec![1u8, 2u8, 3u8].into();
println!("first: {:?}", &*bytes_ref_1);
Arc::get_mut(&mut bytes_ref_1.bytes).map(|v| v.push(4u8));
let bytes_ref_2 = bytes_ref_1.clone();
println!("first': {:?}", &*bytes_ref_1);
println!("second: {:?}", &*bytes_ref_2);
let s: ImStr = "hello".into();
let s2 = s.clone();
println!("S1: {}", s);
println!("S2: {}", s2);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment