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