Advertisement
umuro

string_or_slice.rs

Mar 31st, 2023
1,429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.05 KB | Software | 0 0
  1. use std::rc::Rc;
  2.  
  3. enum StringOrSlice<'a> {
  4.    Owned(String),
  5.    Borrowed(&'a str),
  6. }
  7.  
  8. struct MyString<'a> {
  9.    data: StringOrSlice<'a>,
  10. }
  11.  
  12. impl<'a> MyString<'a> {
  13.     fn new_owned(data: String) -> Self {
  14.         MyString {
  15.             data: StringOrSlice::Owned(data),
  16.         }
  17.     }
  18.  
  19.     fn new_borrowed(data: &'a str) -> Self {
  20.        MyString {
  21.            data: StringOrSlice::Borrowed(data),
  22.        }
  23.    }
  24.  
  25.    fn as_ref(&self) -> &str {
  26.        match &self.data {
  27.            StringOrSlice::Owned(s) => &s,
  28.            StringOrSlice::Borrowed(s) => s,
  29.        }
  30.    }
  31.  
  32.    fn clone(&self) -> Self {
  33.        match &self.data {
  34.            StringOrSlice::Owned(s) => MyString::new_owned(s.clone()),
  35.            StringOrSlice::Borrowed(s) => MyString::new_borrowed(s),
  36.        }
  37.    }
  38.  
  39.    fn to_owned(&self) -> MyString<'static> {
  40.         match &self.data {
  41.             StringOrSlice::Owned(s) => MyString::new_owned(s.clone()),
  42.             StringOrSlice::Borrowed(s) => MyString::new_owned(s.to_owned()),
  43.         }
  44.     }
  45. }
  46.  
Tags: optimization
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement