Created
June 7, 2019 20:54
-
-
Save rust-play/586ee29aa2b6249065902777fae160d7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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