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
use std::fmt;
use std::io::{self, Write};
pub struct BytesWriter {
buf: bytes::BytesMut,
}
impl BytesWriter {
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
buf: bytes::BytesMut::with_capacity(capacity)
}
}
#[inline]
pub fn freeze(self) -> bytes::Bytes {
self.buf.freeze()
}
}
impl Default for BytesWriter {
fn default() -> Self {
Self::with_capacity(0)
}
}
impl Into<bytes::Bytes> for BytesWriter {
#[inline]
fn into(self) -> bytes::Bytes {
self.freeze()
}
}
impl io::Write for BytesWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.buf.extend_from_slice(buf);
Ok(buf.len())
}
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.buf.extend_from_slice(buf);
Ok(())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl fmt::Write for BytesWriter {
fn write_str(&mut self, text: &str) -> fmt::Result {
self.buf.extend_from_slice(text.as_bytes());
Ok(())
}
}
pub fn display_to_header<T: fmt::Display>(data: &T) -> http::header::HeaderValue {
let mut res = BytesWriter::default();
let _ = write!(&mut res, "{}", data);
unsafe { http::header::HeaderValue::from_shared_unchecked(res.freeze()) }
}