#![deny(warnings, missing_docs, missing_debug_implementations)]
#![doc(html_root_url = "https://docs.rs/string/0.1.0")]
use std::{fmt, ops, str};
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)]
pub struct String<T = Vec<u8>> {
value: T,
}
impl<T> String<T> {
pub fn get_ref(&self) -> &T {
&self.value
}
pub unsafe fn get_mut(&mut self) -> &mut T {
&mut self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
impl String {
pub fn new() -> String {
String::default()
}
}
impl<T> String<T>
where T: AsRef<[u8]>,
{
pub unsafe fn from_utf8_unchecked(value: T) -> String<T> {
String { value }
}
}
impl<T> ops::Deref for String<T>
where T: AsRef<[u8]>
{
type Target = str;
#[inline]
fn deref(&self) -> &str {
let b = self.value.as_ref();
unsafe { str::from_utf8_unchecked(b) }
}
}
impl From<::std::string::String> for String<::std::string::String> {
fn from(value: ::std::string::String) -> Self {
String { value }
}
}
impl<'a> From<&'a str> for String<&'a str> {
fn from(value: &'a str) -> Self {
String { value }
}
}
impl<T> TryFrom<T> for String<T>
where T: AsRef<[u8]>
{
type Error = str::Utf8Error;
fn try_from(value: T) -> Result<Self, Self::Error> {
let _ = str::from_utf8(value.as_ref())?;
Ok(String { value })
}
}
impl<T: AsRef<[u8]>> fmt::Debug for String<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(fmt)
}
}
pub trait TryFrom<T>: Sized + sealed::Sealed {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}
impl<T> sealed::Sealed for String<T> {}
mod sealed {
pub trait Sealed {}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_std_string() {
let s: String<_> = "hello".to_string().into();
assert_eq!(&s[..], "hello");
}
}