gix_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: u64) -> 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], out: &mut dyn io::Write) -> io::Result<()> {
38    let mut lines = value.as_bstr().lines_with_terminator();
39    out.write_all(name)?;
40    out.write_all(SPACE)?;
41    out.write_all(lines.next().ok_or(Error::EmptyValue)?)?;
42    for line in lines {
43        out.write_all(SPACE)?;
44        out.write_all(line)?;
45    }
46    if !value.ends_with_str(b"\n") {
47        out.write_all(NL)?;
48    }
49    Ok(())
50}
51
52pub(crate) fn trusted_header_field(name: &[u8], value: &[u8], out: &mut dyn io::Write) -> io::Result<()> {
53    out.write_all(name)?;
54    out.write_all(SPACE)?;
55    out.write_all(value)?;
56    out.write_all(NL)
57}
58
59pub(crate) fn trusted_header_signature(
60    name: &[u8],
61    value: &gix_actor::SignatureRef<'_>,
62    out: &mut dyn io::Write,
63) -> io::Result<()> {
64    out.write_all(name)?;
65    out.write_all(SPACE)?;
66    value.write_to(out)?;
67    out.write_all(NL)
68}
69
70pub(crate) fn trusted_header_id(
71    name: &[u8],
72    value: &gix_hash::ObjectId,
73    mut out: &mut dyn io::Write,
74) -> io::Result<()> {
75    out.write_all(name)?;
76    out.write_all(SPACE)?;
77    value.write_hex_to(&mut out)?;
78    out.write_all(NL)
79}
80
81pub(crate) fn header_field(name: &[u8], value: &[u8], out: &mut dyn io::Write) -> io::Result<()> {
82    if value.is_empty() {
83        return Err(Error::EmptyValue.into());
84    }
85    if value.find(NL).is_some() {
86        return Err(Error::NewlineInHeaderValue { value: value.into() }.into());
87    }
88    trusted_header_field(name, value, out)
89}
90
91pub(crate) const NL: &[u8; 1] = b"\n";
92pub(crate) const SPACE: &[u8; 1] = b" ";