emote_psb\types/
string.rs1use std::io::{Read, Write};
8
9use crate::{PsbError, PsbErrorKind, PsbRefs};
10
11#[cfg(feature = "serde")]
12use serde::{Serialize, Deserialize};
13
14use super::reference::PsbStringRef;
15
16#[derive(Debug, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
18#[cfg_attr(feature = "serde", serde(transparent))]
19pub struct PsbString {
20
21 string: String
22
23}
24
25impl PsbString {
26
27 pub fn new() -> Self {
28 Self {
29 string: String::new()
30 }
31 }
32
33 pub fn string(&self) -> &String {
34 &self.string
35 }
36
37 pub fn string_mut(&mut self) -> &mut String {
38 &mut self.string
39 }
40
41 pub fn set_string(&mut self, string: String) {
42 self.string = string;
43 }
44
45 pub fn unwrap(self) -> String {
46 self.string
47 }
48
49 pub fn from_bytes(n: u8, stream: &mut impl Read, table: &PsbRefs) -> Result<(u64, Self), PsbError> {
50 let (read, reference) = PsbStringRef::from_bytes(n, stream)?;
51
52 let string = table.get_string(reference.string_ref as usize);
53
54 if string.is_none() {
55 return Err(PsbError::new(PsbErrorKind::InvalidOffsetTable, None));
56 }
57
58 Ok((read, Self::from(string.unwrap().clone())))
59 }
60
61 pub fn write_bytes(&self, stream: &mut impl Write, ref_table: &PsbRefs) -> Result<u64, PsbError> {
63 match ref_table.find_string_index(&self.string) {
64
65 Some(ref_index) => {
66 PsbStringRef { string_ref: ref_index }.write_bytes(stream)
67 },
68
69 None => Err(PsbError::new(PsbErrorKind::InvalidOffsetTable, None))
70 }
71 }
72
73}
74
75impl From<String> for PsbString {
76
77 fn from(string: String) -> Self {
78 Self { string }
79 }
80
81}