Guest User

Untitled

a guest
Apr 21st, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. use std::borrow::{Borrow, BorrowMut};
  2. use std::fmt::Debug;
  3. use std::fmt::Error;
  4. use std::fmt::Formatter;
  5. use std::borrow::ToOwned;
  6. use std::ops::{Deref, DerefMut};
  7.  
  8. #[derive(PartialEq, Eq)]
  9. struct MyString(String);
  10.  
  11. impl Debug for MyString {
  12. fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
  13. write!(f, "MyString")
  14. }
  15. }
  16.  
  17. impl From<String> for MyString {
  18. fn from(s: String) -> MyString {
  19. MyString(s)
  20. }
  21. }
  22.  
  23. #[derive(PartialEq, Eq)]
  24. struct MyStr(str);
  25.  
  26. impl<'a> Debug for &'a MyStr {
  27. fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
  28. write!(f, "MyStr")
  29. }
  30. }
  31.  
  32. impl<'a> From<&'a str> for &'a MyStr {
  33. fn from(s: &'a str) -> &'a MyStr {
  34. unsafe { std::mem::transmute(s) }
  35. }
  36. }
  37.  
  38. impl<'a> From<&'a mut str> for &'a mut MyStr {
  39. fn from(s: &'a mut str) -> &'a mut MyStr {
  40. unsafe { std::mem::transmute(s) }
  41. }
  42. }
  43.  
  44. impl<'a> Borrow<MyStr> for MyString {
  45. fn borrow<'b>(&'b self) -> &'b MyStr {
  46. self.0.as_str().into()
  47. }
  48. }
  49.  
  50. impl<'a> BorrowMut<MyStr> for MyString {
  51. fn borrow_mut<'b>(&'b mut self) -> &'b mut MyStr {
  52. self.0.as_mut_str().into()
  53. }
  54. }
  55.  
  56. impl ToOwned for MyStr {
  57. type Owned = MyString;
  58. fn to_owned(&self) -> Self::Owned {
  59. MyString(self.0.to_owned())
  60. }
  61. }
  62.  
  63. impl Deref for MyString {
  64. type Target = MyStr;
  65. fn deref(&self) -> &Self::Target {
  66. self.borrow()
  67. }
  68. }
  69.  
  70. impl DerefMut for MyString {
  71. fn deref_mut(&mut self) -> &mut Self::Target {
  72. self.borrow_mut()
  73. }
  74. }
  75.  
  76. fn main() {
  77. let s: MyString = "foo".to_string().into();
  78. println!("{:?}", s);
  79. let s: &MyStr = "foo".into();
  80. println!("{:?}", s);
  81. }
Add Comment
Please, Sign In to add comment