pub struct Header<'a> { /* private fields */ }
Expand description

A parsed section header, containing a name and optionally a subsection name.

Implementations§

Instantiate a new header either with a section name, e.g. “core” serializing to ["core"] or [remote "origin"] for subsection being “origin” and name being “remote”.

Examples found in repository?
src/file/section/mod.rs (line 39)
33
34
35
36
37
38
39
40
41
42
43
44
    pub fn new(
        name: impl Into<Cow<'a, str>>,
        subsection: impl Into<Option<Cow<'a, BStr>>>,
        meta: impl Into<OwnShared<file::Metadata>>,
    ) -> Result<Self, parse::section::header::Error> {
        Ok(Section {
            header: parse::section::Header::new(name, subsection)?,
            body: Default::default(),
            meta: meta.into(),
            id: SectionId::default(),
        })
    }
More examples
Hide additional examples
src/file/access/mutate.rs (line 304)
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    pub fn rename_section<'a>(
        &mut self,
        name: impl AsRef<str>,
        subsection_name: impl Into<Option<&'a BStr>>,
        new_name: impl Into<Cow<'event, str>>,
        new_subsection_name: impl Into<Option<Cow<'event, BStr>>>,
    ) -> Result<(), rename_section::Error> {
        let id = self
            .section_ids_by_name_and_subname(name.as_ref(), subsection_name.into())?
            .rev()
            .next()
            .expect("list of sections were empty, which violates invariant");
        let section = self.sections.get_mut(&id).expect("known section-id");
        section.header = section::Header::new(new_name, new_subsection_name)?;
        Ok(())
    }

    /// Renames the section with `name` and `subsection_name`, modifying the last matching section
    /// that also passes `filter` to use `new_name` and `new_subsection_name`.
    ///
    /// Note that the otherwise unused [`lookup::existing::Error::KeyMissing`] variant is used to indicate
    /// that the `filter` rejected all candidates, leading to no section being renamed after all.
    pub fn rename_section_filter<'a>(
        &mut self,
        name: impl AsRef<str>,
        subsection_name: impl Into<Option<&'a BStr>>,
        new_name: impl Into<Cow<'event, str>>,
        new_subsection_name: impl Into<Option<Cow<'event, BStr>>>,
        filter: &mut MetadataFilter,
    ) -> Result<(), rename_section::Error> {
        let id = self
            .section_ids_by_name_and_subname(name.as_ref(), subsection_name.into())?
            .rev()
            .find(|id| filter(self.sections.get(id).expect("each id has a section").meta()))
            .ok_or(rename_section::Error::Lookup(lookup::existing::Error::KeyMissing))?;
        let section = self.sections.get_mut(&id).expect("known section-id");
        section.header = section::Header::new(new_name, new_subsection_name)?;
        Ok(())
    }

Return true if this is a header like [legacy.subsection], or false otherwise.

Return the subsection name, if present, i.e. “origin” in [remote "origin"].

It is parsed without quotes, and with escapes folded into their resulting characters. Thus during serialization, escapes and quotes must be re-added. This makes it possible to use Event data for lookups directly.

Return the name of the header, like “remote” in [remote "origin"].

Serialize this type into a BString for convenience.

Note that to_string() can also be used, but might not be lossless.

Examples found in repository?
src/parse/section/header.rs (line 160)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.to_bstring(), f)
    }
}

impl From<Header<'_>> for BString {
    fn from(header: Header<'_>) -> Self {
        header.into()
    }
}

impl From<&Header<'_>> for BString {
    fn from(header: &Header<'_>) -> Self {
        header.to_bstring()
    }

Stream ourselves to the given out, in order to reproduce this header mostly losslessly as it was parsed.

Examples found in repository?
src/parse/section/header.rs (line 107)
105
106
107
108
109
    pub fn to_bstring(&self) -> BString {
        let mut buf = Vec::new();
        self.write_to(&mut buf).expect("io error impossible");
        buf.into()
    }
More examples
Hide additional examples
src/parse/event.rs (line 45)
36
37
38
39
40
41
42
43
44
45
46
47
48
    pub fn write_to(&self, mut out: impl std::io::Write) -> std::io::Result<()> {
        match self {
            Self::ValueNotDone(e) => {
                out.write_all(e.as_ref())?;
                out.write_all(b"\\")
            }
            Self::Whitespace(e) | Self::Newline(e) | Self::Value(e) | Self::ValueDone(e) => out.write_all(e.as_ref()),
            Self::KeyValueSeparator => out.write_all(b"="),
            Self::SectionKey(k) => out.write_all(k.0.as_ref()),
            Self::SectionHeader(h) => h.write_to(&mut out),
            Self::Comment(c) => c.write_to(&mut out),
        }
    }
src/file/section/mod.rs (line 78)
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    pub fn write_to(&self, mut out: impl std::io::Write) -> std::io::Result<()> {
        self.header.write_to(&mut out)?;

        if self.body.0.is_empty() {
            return Ok(());
        }

        let nl = self
            .body
            .as_ref()
            .iter()
            .find_map(extract_newline)
            .unwrap_or_else(|| platform_newline());

        if !self
            .body
            .as_ref()
            .iter()
            .take_while(|e| !matches!(e, Event::SectionKey(_)))
            .any(|e| e.to_bstr_lossy().contains_str(nl))
        {
            out.write_all(nl)?;
        }

        let mut saw_newline_after_value = true;
        let mut in_key_value_pair = false;
        for (idx, event) in self.body.as_ref().iter().enumerate() {
            match event {
                Event::SectionKey(_) => {
                    if !saw_newline_after_value {
                        out.write_all(nl)?;
                    }
                    saw_newline_after_value = false;
                    in_key_value_pair = true;
                }
                Event::Newline(_) if !in_key_value_pair => {
                    saw_newline_after_value = true;
                }
                Event::Value(_) | Event::ValueDone(_) => {
                    in_key_value_pair = false;
                }
                _ => {}
            }
            event.write_to(&mut out)?;
            if let Event::ValueNotDone(_) = event {
                if self
                    .body
                    .0
                    .get(idx + 1)
                    .filter(|e| matches!(e, Event::Newline(_)))
                    .is_none()
                {
                    out.write_all(nl)?;
                }
            }
        }
        Ok(())
    }

Turn this instance into a fully owned one with 'static lifetime.

Examples found in repository?
src/parse/section/mod.rs (line 35)
33
34
35
36
37
38
    pub fn to_owned(&self) -> Section<'static> {
        Section {
            header: self.header.to_owned(),
            events: self.events.iter().map(Event::to_owned).collect(),
        }
    }
More examples
Hide additional examples
src/parse/event.rs (line 55)
52
53
54
55
56
57
58
59
60
61
62
63
64
    pub fn to_owned(&self) -> Event<'static> {
        match self {
            Event::Comment(e) => Event::Comment(e.to_owned()),
            Event::SectionHeader(e) => Event::SectionHeader(e.to_owned()),
            Event::SectionKey(e) => Event::SectionKey(e.to_owned()),
            Event::Value(e) => Event::Value(Cow::Owned(e.clone().into_owned())),
            Event::ValueNotDone(e) => Event::ValueNotDone(Cow::Owned(e.clone().into_owned())),
            Event::ValueDone(e) => Event::ValueDone(Cow::Owned(e.clone().into_owned())),
            Event::Newline(e) => Event::Newline(Cow::Owned(e.clone().into_owned())),
            Event::Whitespace(e) => Event::Whitespace(Cow::Owned(e.clone().into_owned())),
            Event::KeyValueSeparator => Event::KeyValueSeparator,
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.