gix_config/file/mutable/
value.rs

1use std::borrow::Cow;
2
3use bstr::BStr;
4
5use crate::{
6    file,
7    file::{mutable::section::SectionMut, Index, Size},
8    lookup,
9    parse::section,
10};
11
12/// An intermediate representation of a mutable value obtained from a [`File`][crate::File].
13#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
14pub struct ValueMut<'borrow, 'lookup, 'event> {
15    pub(crate) section: SectionMut<'borrow, 'event>,
16    pub(crate) key: section::ValueName<'lookup>,
17    pub(crate) index: Index,
18    pub(crate) size: Size,
19}
20
21impl<'borrow, 'event> ValueMut<'borrow, '_, 'event> {
22    /// Returns the actual value. This is computed each time this is called
23    /// requiring an allocation for multi-line values.
24    pub fn get(&self) -> Result<Cow<'_, BStr>, lookup::existing::Error> {
25        self.section.get(&self.key, self.index, self.index + self.size)
26    }
27
28    /// Update the value to the provided one. This modifies the value such that
29    /// the Value event(s) are replaced with a single new event containing the
30    /// new value.
31    pub fn set_string(&mut self, input: impl AsRef<str>) {
32        self.set(input.as_ref());
33    }
34
35    /// Update the value to the provided one. This modifies the value such that
36    /// the Value event(s) are replaced with a single new event containing the
37    /// new value.
38    pub fn set<'a>(&mut self, input: impl Into<&'a BStr>) {
39        if self.size.0 > 0 {
40            self.section.delete(self.index, self.index + self.size);
41        }
42        self.size = self.section.set_internal(self.index, self.key.to_owned(), input.into());
43    }
44
45    /// Removes the value. Does nothing when called multiple times in
46    /// succession.
47    pub fn delete(&mut self) {
48        if self.size.0 > 0 {
49            self.section.delete(self.index, self.index + self.size);
50            self.size = Size(0);
51        }
52    }
53
54    /// Return the section containing the value.
55    pub fn section(&self) -> &file::Section<'event> {
56        &self.section
57    }
58
59    /// Convert this value into its owning mutable section.
60    pub fn into_section_mut(self) -> file::SectionMut<'borrow, 'event> {
61        self.section
62    }
63}