musli_common/buf/
buf_string.rs

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use core::fmt::{self, Write};
use core::ops::Deref;
use core::str;

use musli::{Buf, Context};

use crate::fixed::CapacityError;

/// A string wrapped around a context buffer.
pub struct BufString<B> {
    buf: B,
}

/// Collect a string into a string buffer.
pub fn collect_string<C, T>(cx: &C, value: T) -> Result<BufString<C::Buf<'_>>, C::Error>
where
    C: ?Sized + Context,
    T: fmt::Display,
{
    let Some(buf) = cx.alloc() else {
        return Err(cx.message("Failed to allocate"));
    };

    let mut string = BufString::new(buf);

    if write!(string, "{value}").is_err() {
        return Err(cx.message("Failed to write to string"));
    }

    Ok(string)
}

/// Try to collect a string into a string buffer.
pub fn try_collect_string<C, T>(cx: &C, value: T) -> Option<BufString<C::Buf<'_>>>
where
    C: ?Sized + Context,
    T: fmt::Display,
{
    let buf = cx.alloc()?;
    let mut string = BufString::new(buf);
    write!(string, "{value}").ok()?;
    Some(string)
}

impl<B> BufString<B>
where
    B: Buf,
{
    /// Construct a new fixed string.
    pub const fn new(buf: B) -> BufString<B> {
        BufString { buf }
    }

    fn as_str(&self) -> &str {
        // SAFETY: Interactions ensure that data is valid utf-8.
        unsafe { str::from_utf8_unchecked(self.buf.as_slice()) }
    }

    fn try_push(&mut self, c: char) -> Result<(), CapacityError> {
        if !self.buf.write(c.encode_utf8(&mut [0; 4]).as_bytes()) {
            return Err(CapacityError);
        }

        Ok(())
    }

    fn try_push_str(&mut self, s: &str) -> Result<(), CapacityError> {
        if !self.buf.write(s.as_bytes()) {
            return Err(CapacityError);
        }

        Ok(())
    }
}

impl<B> fmt::Write for BufString<B>
where
    B: Buf,
{
    fn write_char(&mut self, c: char) -> fmt::Result {
        self.try_push(c).map_err(|_| fmt::Error)
    }

    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.try_push_str(s).map_err(|_| fmt::Error)
    }
}

impl<B> Deref for BufString<B>
where
    B: Buf,
{
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        unsafe { str::from_utf8_unchecked(self.buf.as_slice()) }
    }
}

impl<B> fmt::Display for BufString<B>
where
    B: Buf,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl<B> AsRef<str> for BufString<B>
where
    B: Buf,
{
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}