toe_beans/v4/message/options/
string.rs

1use crate::v4::error::Result;
2use serde::{Deserialize, Serialize};
3
4/// An option that represents a string of variable length with a minimum length of 1.
5#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
6pub struct StringOption(String);
7
8impl StringOption {
9    /// Create a `StringOption`. Length must be greater than 0.
10    pub fn new(value: String) -> Result<Self> {
11        if value.is_empty() {
12            return Err("Must have length of at least 1");
13        }
14
15        Ok(Self(value))
16    }
17
18    /// Used, when serializing, to add to the byte buffer.
19    #[inline]
20    pub fn extend_into(&self, bytes: &mut Vec<u8>, tag: u8) {
21        bytes.push(tag); // tag
22        bytes.push(self.0.len() as u8); // length
23        bytes.extend_from_slice(self.0.as_bytes()); // value
24    }
25}
26
27impl TryFrom<String> for StringOption {
28    type Error = &'static str;
29
30    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
31        StringOption::new(value)
32    }
33}
34
35impl From<&[u8]> for StringOption {
36    fn from(value: &[u8]) -> Self {
37        Self(String::from_utf8_lossy(value).to_string())
38    }
39}