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
|
//! Encoding utilities
use std::io::{self, Write};
use bstr::{BString, ByteSlice};
/// An error returned when object encoding fails.
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error("Newlines are not allowed in header values: {value:?}")]
NewlineInHeaderValue { value: BString },
#[error("Header values must not be empty")]
EmptyValue,
}
macro_rules! check {
($e: expr) => {
$e.expect("Writing to a Vec should never fail.")
};
}
/// Generates a loose header buffer
pub fn loose_header(kind: crate::Kind, size: usize) -> smallvec::SmallVec<[u8; 28]> {
let mut v = smallvec::SmallVec::new();
check!(v.write_all(kind.as_bytes()));
check!(v.write_all(SPACE));
check!(v.write_all(itoa::Buffer::new().format(size).as_bytes()));
check!(v.write_all(b"\0"));
v
}
impl From<Error> for io::Error {
fn from(other: Error) -> io::Error {
io::Error::new(io::ErrorKind::Other, other)
}
}
pub(crate) fn header_field_multi_line(name: &[u8], value: &[u8], mut out: impl io::Write) -> io::Result<()> {
let mut lines = value.as_bstr().split_str(b"\n");
trusted_header_field(name, lines.next().ok_or(Error::EmptyValue)?, &mut out)?;
for line in lines {
out.write_all(SPACE)?;
out.write_all(line)?;
out.write_all(NL)?;
}
Ok(())
}
pub(crate) fn trusted_header_field(name: &[u8], value: &[u8], mut out: impl io::Write) -> io::Result<()> {
out.write_all(name)?;
out.write_all(SPACE)?;
out.write_all(value)?;
out.write_all(NL)
}
pub(crate) fn trusted_header_signature(
name: &[u8],
value: &gix_actor::SignatureRef<'_>,
mut out: impl io::Write,
) -> io::Result<()> {
out.write_all(name)?;
out.write_all(SPACE)?;
value.write_to(&mut out)?;
out.write_all(NL)
}
pub(crate) fn trusted_header_id(name: &[u8], value: &gix_hash::ObjectId, mut out: impl io::Write) -> io::Result<()> {
out.write_all(name)?;
out.write_all(SPACE)?;
value.write_hex_to(&mut out)?;
out.write_all(NL)
}
pub(crate) fn header_field(name: &[u8], value: &[u8], out: impl io::Write) -> io::Result<()> {
if value.is_empty() {
return Err(Error::EmptyValue.into());
}
if value.find(NL).is_some() {
return Err(Error::NewlineInHeaderValue { value: value.into() }.into());
}
trusted_header_field(name, value, out)
}
pub(crate) const NL: &[u8; 1] = b"\n";
pub(crate) const SPACE: &[u8; 1] = b" ";
|