1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
7 //! A replacement for `Box<str>` that has a defined layout for FFI.
9 use crate::owned_slice::OwnedSlice;
11 use std::ops::{Deref, DerefMut};
13 /// A struct that basically replaces a Box<str>, but with a defined layout,
16 #[derive(Clone, Default, Eq, MallocSizeOf, PartialEq, ToShmem)]
17 pub struct OwnedStr(OwnedSlice<u8>);
19 impl fmt::Debug for OwnedStr {
20 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
21 self.deref().fmt(formatter)
25 impl Deref for OwnedStr {
29 fn deref(&self) -> &Self::Target {
30 unsafe { std::str::from_utf8_unchecked(&*self.0) }
34 impl DerefMut for OwnedStr {
36 fn deref_mut(&mut self) -> &mut Self::Target {
37 unsafe { std::str::from_utf8_unchecked_mut(&mut *self.0) }
42 /// Convert the OwnedStr into a boxed str.
44 pub fn into_box(self) -> Box<str> {
45 self.into_string().into_boxed_str()
48 /// Convert the OwnedStr into a `String`.
50 pub fn into_string(self) -> String {
51 unsafe { String::from_utf8_unchecked(self.0.into_vec()) }
55 impl From<OwnedStr> for String {
57 fn from(b: OwnedStr) -> Self {
62 impl From<OwnedStr> for Box<str> {
64 fn from(b: OwnedStr) -> Self {
69 impl From<Box<str>> for OwnedStr {
71 fn from(b: Box<str>) -> Self {
72 Self::from(b.into_string())
76 impl From<String> for OwnedStr {
78 fn from(s: String) -> Self {
79 OwnedStr(s.into_bytes().into())