Skip to main content

gix_date/parse/
mod.rs

1use std::str::FromStr;
2
3use crate::{Error, Time};
4use smallvec::SmallVec;
5
6/// A container for just enough bytes to hold the largest-possible [`time`](Time) instance.
7/// It's used in conjunction with
8#[derive(Default, Clone)]
9pub struct TimeBuf {
10    buf: SmallVec<[u8; Time::MAX.size()]>,
11}
12
13impl TimeBuf {
14    /// Represent this instance as standard string, serialized in a format compatible with
15    /// signature fields in Git commits, also known as anything parseable as [raw format](function::parse_header()).
16    pub fn as_str(&self) -> &str {
17        // Time serializes as ASCII, which is a subset of UTF-8.
18        let time_bytes = self.buf.as_slice();
19        std::str::from_utf8(time_bytes).expect("time serializes as valid UTF-8")
20    }
21
22    /// Clear the previous content.
23    fn clear(&mut self) {
24        self.buf.clear();
25    }
26}
27
28impl Time {
29    /// Serialize this instance into `buf`, exactly as it would appear in the header of a Git commit,
30    /// and return `buf` as `&str` for easy consumption.
31    pub fn to_str<'a>(&self, buf: &'a mut TimeBuf) -> &'a str {
32        buf.clear();
33        self.write_to(&mut buf.buf)
34            .expect("write to memory of just the right size cannot fail");
35        buf.as_str()
36    }
37}
38
39impl FromStr for Time {
40    type Err = Error;
41
42    fn from_str(s: &str) -> Result<Self, Self::Err> {
43        crate::parse_header(s).ok_or_else(|| Error::new_with_input("invalid time", s))
44    }
45}
46
47pub(crate) mod function;
48mod git;
49mod raw;
50mod relative;