git_object/
encode.rs

1//! Encoding utilities
2use std::io::{self, Write};
3
4use bstr::{BString, ByteSlice};
5
6/// An error returned when object encoding fails.
7#[derive(Debug, thiserror::Error)]
8#[allow(missing_docs)]
9pub enum Error {
10    #[error("Newlines are not allowed in header values: {value:?}")]
11    NewlineInHeaderValue { value: BString },
12    #[error("Header values must not be empty")]
13    EmptyValue,
14}
15
16macro_rules! check {
17    ($e: expr) => {
18        $e.expect("Writing to a Vec should never fail.")
19    };
20}
21/// Generates a loose header buffer
22pub fn loose_header(kind: crate::Kind, size: usize) -> smallvec::SmallVec<[u8; 28]> {
23    let mut v = smallvec::SmallVec::new();
24    check!(v.write_all(kind.as_bytes()));
25    check!(v.write_all(SPACE));
26    check!(v.write_all(itoa::Buffer::new().format(size).as_bytes()));
27    check!(v.write_all(b"\0"));
28    v
29}
30
31impl From<Error> for io::Error {
32    fn from(other: Error) -> io::Error {
33        io::Error::new(io::ErrorKind::Other, other)
34    }
35}
36
37pub(crate) fn header_field_multi_line(name: &[u8], value: &[u8], mut out: impl io::Write) -> io::Result<()> {
38    let mut lines = value.as_bstr().split_str(b"\n");
39    trusted_header_field(name, lines.next().ok_or(Error::EmptyValue)?, &mut out)?;
40    for line in lines {
41        out.write_all(SPACE)?;
42        out.write_all(line)?;
43        out.write_all(NL)?;
44    }
45    Ok(())
46}
47
48pub(crate) fn trusted_header_field(name: &[u8], value: &[u8], mut out: impl io::Write) -> io::Result<()> {
49    out.write_all(name)?;
50    out.write_all(SPACE)?;
51    out.write_all(value)?;
52    out.write_all(NL)
53}
54
55pub(crate) fn trusted_header_signature(
56    name: &[u8],
57    value: &git_actor::SignatureRef<'_>,
58    mut out: impl io::Write,
59) -> io::Result<()> {
60    out.write_all(name)?;
61    out.write_all(SPACE)?;
62    value.write_to(&mut out)?;
63    out.write_all(NL)
64}
65
66pub(crate) fn trusted_header_id(name: &[u8], value: &git_hash::ObjectId, mut out: impl io::Write) -> io::Result<()> {
67    out.write_all(name)?;
68    out.write_all(SPACE)?;
69    value.write_hex_to(&mut out)?;
70    out.write_all(NL)
71}
72
73pub(crate) fn header_field(name: &[u8], value: &[u8], out: impl io::Write) -> io::Result<()> {
74    if value.is_empty() {
75        return Err(Error::EmptyValue.into());
76    }
77    if value.find(NL).is_some() {
78        return Err(Error::NewlineInHeaderValue { value: value.into() }.into());
79    }
80    trusted_header_field(name, value, out)
81}
82
83pub(crate) const NL: &[u8; 1] = b"\n";
84pub(crate) const SPACE: &[u8; 1] = b" ";