Skip to main content

nbt_rs/types/
string.rs

1use core::fmt;
2use std::{
3    borrow::Borrow,
4    hash::{Hash, Hasher},
5    ops::Deref,
6};
7
8use crate::{error::ValidationError, traits::NbtSerialize};
9
10/// A wrapper around a `String` making sure it is a valid nbt string.
11#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord)]
12pub struct NbtString {
13    pub(crate) str: String,
14}
15
16impl fmt::Display for NbtString {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(f, "{}", self.str)
19    }
20}
21
22impl NbtSerialize for NbtString {
23    fn serialize_nbt_payload(&self, buf: &mut Vec<u8>) {
24        let bytes = self.as_bytes();
25        (bytes.len() as u16).serialize_nbt_payload(buf);
26        buf.extend_from_slice(bytes);
27    }
28}
29
30impl Hash for NbtString {
31    fn hash<H: Hasher>(&self, state: &mut H) {
32        self.str.hash(state);
33    }
34}
35
36impl TryFrom<String> for NbtString {
37    type Error = (ValidationError, String);
38
39    /// Attempts to create an `NbtString`
40    ///
41    /// # Errors
42    /// Will fail if the source string is longer than `u16::MAX` bytes.
43    ///
44    /// # Examples
45    /// ```
46    /// let nbt_string: nbt_rs::types::NbtString = "AnNbtString".to_owned().try_into().unwrap();
47    /// ```
48    fn try_from(str: String) -> Result<Self, Self::Error> {
49        if str.len() > u16::MAX as usize {
50            Err((ValidationError::StringTooLong(str.len()), str))
51        } else {
52            Ok(Self { str })
53        }
54    }
55}
56
57impl Deref for NbtString {
58    type Target = str;
59
60    fn deref(&self) -> &Self::Target {
61        &self.str
62    }
63}
64
65impl Borrow<str> for NbtString {
66    fn borrow(&self) -> &str {
67        &self.str
68    }
69}
70
71impl PartialEq<str> for NbtString {
72    fn eq(&self, other: &str) -> bool {
73        self.str == other
74    }
75}
76
77impl PartialEq<NbtString> for str {
78    fn eq(&self, other: &NbtString) -> bool {
79        self == other.str
80    }
81}
82
83impl PartialEq<&str> for NbtString {
84    fn eq(&self, other: &&str) -> bool {
85        self.str == *other
86    }
87}
88
89impl PartialEq<NbtString> for &str {
90    fn eq(&self, other: &NbtString) -> bool {
91        *self == other.str
92    }
93}