1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
crate::use_native_or_external!(List);
crate::use_native_or_external!(StringPtr);

use super::Bytes;

impl Bytes {
    /// Constructs an empty instance of `Bytes`
    pub fn empty() -> Self {
        Self::new(list![])
    }

    /// Converts byte sequence to a string slice, returns error if there are invalid UTF-8 chars
    pub fn as_str_lossy(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(self.as_raw())
    }

    /// Converts byte sequnce to a string, all invalid UTF-8 chars are converted into "replacement char"
    pub fn to_string_lossy(&self) -> StringPtr {
        String::from_utf8_lossy(self.as_raw()).into_owned().into()
    }

    /// Converts byte sequence to a String, returns error if there are invalid UTF-8 chars
    pub fn to_string(&self) -> Result<StringPtr, std::string::FromUtf8Error> {
        String::from_utf8(self.as_raw().to_vec()).map(|s| s.into())
    }

    /// Consumes itself and convrters it into a string, returns error if there are invalid UTF-8 chars
    pub fn into_string(self) -> Result<StringPtr, std::string::FromUtf8Error> {
        String::from_utf8(self.into_raw().into()).map(|s| s.into())
    }

    /// Returns `true` if `self` represents a valid UTF-8 string
    pub fn is_valid_utf8(&self) -> bool {
        std::str::from_utf8(self.as_raw()).is_ok()
    }

    /// Returns `true` if byte sequence is empty
    pub fn is_empty(&self) -> bool {
        self.as_raw().is_empty()
    }

    /// Returns length of the byte sequence
    pub fn len(&self) -> usize {
        self.as_raw().len()
    }

    /// Clears inner data
    pub fn clear(&mut self) {
        self.set_raw(list![])
    }
}