1use std::ops::Deref;
2
3use binrw::binrw;
4
5use super::Bytes;
6
7#[binrw]
11#[derive(Default, Clone, PartialEq, Eq)]
12#[br(assert(std::str::from_utf8(&self_0).is_ok()))]
13pub struct Utf8<'b>(Bytes<'b>);
14
15impl<'b> Utf8<'b> {
16 pub fn owned(value: String) -> Self {
18 Self(Bytes::owned(value.into_bytes()))
19 }
20
21 pub const fn borrowed(value: &'b str) -> Self {
23 Self(Bytes::borrowed(value.as_bytes()))
24 }
25
26 pub fn as_borrow<'a: 'b>(&'a self) -> Utf8<'a> {
28 Self(self.0.as_borrow())
29 }
30
31 pub fn into_string(self) -> String {
33 String::from_utf8(self.0.into_vec()).expect("The inner buffer contained non UTF-8 data")
34 }
35}
36
37impl std::fmt::Debug for Utf8<'_> {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_tuple("Utf8").field(&&**self).finish()
40 }
41}
42
43impl std::fmt::Display for Utf8<'_> {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 f.write_str(self)
46 }
47}
48
49impl Deref for Utf8<'_> {
50 type Target = str;
51
52 fn deref(&self) -> &Self::Target {
53 std::str::from_utf8(&self.0).expect("The inner buffer contained non UTF-8 data")
54 }
55}
56
57impl AsRef<str> for Utf8<'_> {
58 fn as_ref(&self) -> &str {
59 self
60 }
61}
62
63impl From<String> for Utf8<'_> {
64 fn from(value: String) -> Self {
65 Self::owned(value)
66 }
67}
68
69impl<'b> From<&'b str> for Utf8<'b> {
70 fn from(value: &'b str) -> Self {
71 Self::borrowed(value)
72 }
73}