style_traits/
owned_str.rs1#![allow(unsafe_code)]
6
7use crate::owned_slice::OwnedSlice;
10use std::fmt;
11use std::ops::{Deref, DerefMut};
12
13#[repr(C)]
16#[derive(Clone, Default, Eq, MallocSizeOf, PartialEq, ToShmem)]
17pub struct OwnedStr(OwnedSlice<u8>);
18
19impl fmt::Debug for OwnedStr {
20 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
21 self.deref().fmt(formatter)
22 }
23}
24
25impl Deref for OwnedStr {
26 type Target = str;
27
28 #[inline(always)]
29 fn deref(&self) -> &Self::Target {
30 unsafe { std::str::from_utf8_unchecked(&*self.0) }
31 }
32}
33
34impl DerefMut for OwnedStr {
35 #[inline(always)]
36 fn deref_mut(&mut self) -> &mut Self::Target {
37 unsafe { std::str::from_utf8_unchecked_mut(&mut *self.0) }
38 }
39}
40
41impl OwnedStr {
42 #[inline]
44 pub fn into_box(self) -> Box<str> {
45 self.into_string().into_boxed_str()
46 }
47
48 #[inline]
50 pub fn into_string(self) -> String {
51 unsafe { String::from_utf8_unchecked(self.0.into_vec()) }
52 }
53}
54
55impl From<OwnedStr> for String {
56 #[inline]
57 fn from(b: OwnedStr) -> Self {
58 b.into_string()
59 }
60}
61
62impl From<OwnedStr> for Box<str> {
63 #[inline]
64 fn from(b: OwnedStr) -> Self {
65 b.into_box()
66 }
67}
68
69impl From<Box<str>> for OwnedStr {
70 #[inline]
71 fn from(b: Box<str>) -> Self {
72 Self::from(b.into_string())
73 }
74}
75
76impl From<String> for OwnedStr {
77 #[inline]
78 fn from(s: String) -> Self {
79 OwnedStr(s.into_bytes().into())
80 }
81}