gopher_core/
str.rs

1use bytes::Bytes;
2use std::fmt::{self, Debug, Display, Write};
3use std::ops::Deref;
4
5/// A string of bytes as sent over the wire.
6///
7/// The contents are assumed to be encoded in ISO-8859-1 (Latin-1).
8#[derive(Clone)]
9pub struct GopherStr {
10    buf: Bytes
11}
12
13impl GopherStr {
14    /// Create a GopherStr from a Bytes.
15    pub fn new(buf: Bytes) -> Self {
16        GopherStr { buf: buf }
17    }
18
19    pub fn from_latin1(bytes: &[u8]) -> Self {
20        GopherStr { buf: Bytes::from(bytes) }
21    }
22
23    /// Unwrap the inner Bytes.
24    pub fn into_buf(self) -> Bytes {
25        self.buf
26    }
27}
28
29impl Deref for GopherStr {
30    type Target = [u8];
31    fn deref(&self) -> &[u8] {
32        &self.buf
33    }
34}
35
36impl Display for GopherStr {
37    /// Decode from Latin-1 without allocating.
38    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39        for b in &self.buf {
40            f.write_char(b as char)?;
41        }
42        Ok(())
43    }
44}
45
46impl Debug for GopherStr {
47    /// Decode from Latin-1 without allocating.
48    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
49        f.write_char('"')?;
50        for b in &self.buf {
51            for c in (b as char).escape_default() {
52                f.write_char(c)?;
53            }
54        }
55        f.write_char('"')?;
56        Ok(())
57    }
58}