Advertisement
umuro

data_container.rs

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