1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::{
    borrow::{Borrow, Cow},
    collections::HashMap,
    ops::DerefMut,
};

use crate::{
    file::{
        error::GitConfigError,
        git_config::SectionId,
        section::{MutableSection, SectionBody},
        Index, Size,
    },
    parser::{Event, Key},
    values::{normalize_bytes, normalize_vec},
};

/// An intermediate representation of a mutable value obtained from
/// [`GitConfig`].
///
/// This holds a mutable reference to the underlying data structure of
/// [`GitConfig`], and thus guarantees through Rust's borrower checker that
/// multiple mutable references to [`GitConfig`] cannot be owned at the same
/// time.
///
/// [`GitConfig`]: super::GitConfig
#[allow(clippy::module_name_repetitions)]
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct MutableValue<'borrow, 'lookup, 'event> {
    section: MutableSection<'borrow, 'event>,
    key: Key<'lookup>,
    index: Index,
    size: Size,
}

impl<'borrow, 'lookup, 'event> MutableValue<'borrow, 'lookup, 'event> {
    pub(super) const fn new(
        section: MutableSection<'borrow, 'event>,
        key: Key<'lookup>,
        index: Index,
        size: Size,
    ) -> Self {
        Self {
            section,
            key,
            index,
            size,
        }
    }

    /// Returns the actual value. This is computed each time this is called, so
    /// it's best to reuse this value or own it if an allocation is acceptable.
    ///
    /// # Errors
    ///
    /// Returns an error if the lookup failed.
    #[inline]
    pub fn get(&self) -> Result<Cow<'_, [u8]>, GitConfigError> {
        self.section.get(&self.key, self.index, self.index + self.size)
    }

    /// Update the value to the provided one. This modifies the value such that
    /// the Value event(s) are replaced with a single new event containing the
    /// new value.
    #[inline]
    pub fn set_string(&mut self, input: String) {
        self.set_bytes(input.into_bytes());
    }

    /// Update the value to the provided one. This modifies the value such that
    /// the Value event(s) are replaced with a single new event containing the
    /// new value.
    pub fn set_bytes(&mut self, input: Vec<u8>) {
        if self.size.0 > 0 {
            self.section.delete(self.index, self.index + self.size);
        }
        self.size = Size(3);
        self.section
            .set_internal(self.index, Key(Cow::Owned(self.key.to_string())), input);
    }

    /// Removes the value. Does nothing when called multiple times in
    /// succession.
    pub fn delete(&mut self) {
        if self.size.0 > 0 {
            self.section.delete(self.index, self.index + self.size);
            self.size = Size(0);
        }
    }
}

/// Internal data structure for [`MutableMultiValue`]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub(super) struct EntryData {
    section_id: SectionId,
    offset_index: usize,
}

impl EntryData {
    pub(super) const fn new(section_id: SectionId, offset_index: usize) -> Self {
        Self {
            section_id,
            offset_index,
        }
    }
}

/// An intermediate representation of a mutable multivar obtained from
/// [`GitConfig`].
///
/// This holds a mutable reference to the underlying data structure of
/// [`GitConfig`], and thus guarantees through Rust's borrower checker that
/// multiple mutable references to [`GitConfig`] cannot be owned at the same
/// time.
///
/// [`GitConfig`]: super::GitConfig
#[allow(clippy::module_name_repetitions)]
#[derive(PartialEq, Eq, Debug)]
pub struct MutableMultiValue<'borrow, 'lookup, 'event> {
    section: &'borrow mut HashMap<SectionId, SectionBody<'event>>,
    key: Key<'lookup>,
    /// Each entry data struct provides sufficient information to index into
    /// [`Self::offsets`]. This layer of indirection is used for users to index
    /// into the offsets rather than leaking the internal data structures.
    indices_and_sizes: Vec<EntryData>,
    /// Each offset represents the size of a event slice and whether or not the
    /// event slice is significant or not. This is used to index into the
    /// actual section.
    offsets: HashMap<SectionId, Vec<usize>>,
}

impl<'borrow, 'lookup, 'event> MutableMultiValue<'borrow, 'lookup, 'event> {
    pub(super) fn new(
        section: &'borrow mut HashMap<SectionId, SectionBody<'event>>,
        key: Key<'lookup>,
        indices_and_sizes: Vec<EntryData>,
        offsets: HashMap<SectionId, Vec<usize>>,
    ) -> Self {
        Self {
            section,
            key,
            indices_and_sizes,
            offsets,
        }
    }

    /// Returns the actual values. This is computed each time this is called.
    ///
    /// # Errors
    ///
    /// Returns an error if the lookup failed.
    pub fn get(&self) -> Result<Vec<Cow<'_, [u8]>>, GitConfigError> {
        let mut found_key = false;
        let mut values = vec![];
        let mut partial_value = None;
        // section_id is guaranteed to exist in self.sections, else we have a
        // violated invariant.
        for EntryData {
            section_id,
            offset_index,
        } in &self.indices_and_sizes
        {
            let (offset, size) = MutableMultiValue::get_index_and_size(&self.offsets, *section_id, *offset_index);
            for event in &self
                .section
                .get(section_id)
                .expect("sections does not have section id from section ids")
                .as_ref()[offset..offset + size]
            {
                match event {
                    Event::Key(event_key) if *event_key == self.key => found_key = true,
                    Event::Value(v) if found_key => {
                        found_key = false;
                        values.push(normalize_bytes(v.borrow()));
                    }
                    Event::ValueNotDone(v) if found_key => {
                        partial_value = Some((*v).to_vec());
                    }
                    Event::ValueDone(v) if found_key => {
                        found_key = false;
                        let mut value = partial_value
                            .take()
                            .expect("Somehow got ValueDone before ValueNotDone event");
                        value.extend(&**v);
                        values.push(normalize_vec(value));
                    }
                    _ => (),
                }
            }
        }

        if values.is_empty() {
            return Err(GitConfigError::KeyDoesNotExist);
        }

        Ok(values)
    }

    /// Returns the size of values the multivar has.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.indices_and_sizes.len()
    }

    /// Returns if the multivar has any values. This might occur if the value
    /// was deleted but not set with a new value.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.indices_and_sizes.is_empty()
    }

    /// Sets the value at the given index.
    ///
    /// # Safety
    ///
    /// This will panic if the index is out of range.
    #[inline]
    pub fn set_string(&mut self, index: usize, input: String) {
        self.set_bytes(index, input.into_bytes());
    }

    /// Sets the value at the given index.
    ///
    /// # Safety
    ///
    /// This will panic if the index is out of range.
    #[inline]
    pub fn set_bytes(&mut self, index: usize, input: Vec<u8>) {
        self.set_value(index, Cow::Owned(input));
    }

    /// Sets the value at the given index.
    ///
    /// # Safety
    ///
    /// This will panic if the index is out of range.
    pub fn set_value<'a: 'event>(&mut self, index: usize, input: Cow<'a, [u8]>) {
        let EntryData {
            section_id,
            offset_index,
        } = self.indices_and_sizes[index];
        MutableMultiValue::set_value_inner(
            &self.key,
            &mut self.offsets,
            self.section
                .get_mut(&section_id)
                .expect("sections does not have section id from section ids"),
            section_id,
            offset_index,
            input,
        );
    }

    /// Sets all values to the provided values. Note that this follows [`zip`]
    /// logic: if the number of values in the input is less than the number of
    /// values currently existing, then only the first `n` values are modified.
    /// If more values are provided than there currently are, then the
    /// remaining values are ignored.
    ///
    /// [`zip`]: std::iter::Iterator::zip
    #[inline]
    pub fn set_values<'a: 'event>(&mut self, input: impl Iterator<Item = Cow<'a, [u8]>>) {
        for (
            EntryData {
                section_id,
                offset_index,
            },
            value,
        ) in self.indices_and_sizes.iter().zip(input)
        {
            Self::set_value_inner(
                &self.key,
                &mut self.offsets,
                self.section
                    .get_mut(section_id)
                    .expect("sections does not have section id from section ids"),
                *section_id,
                *offset_index,
                value,
            );
        }
    }

    /// Sets all values in this multivar to the provided one by copying the
    /// input for all values.
    #[inline]
    pub fn set_str_all(&mut self, input: &str) {
        self.set_owned_values_all(input.as_bytes());
    }

    /// Sets all values in this multivar to the provided one by copying the
    /// input bytes for all values.
    #[inline]
    pub fn set_owned_values_all(&mut self, input: &[u8]) {
        for EntryData {
            section_id,
            offset_index,
        } in &self.indices_and_sizes
        {
            Self::set_value_inner(
                &self.key,
                &mut self.offsets,
                self.section
                    .get_mut(section_id)
                    .expect("sections does not have section id from section ids"),
                *section_id,
                *offset_index,
                Cow::Owned(input.to_vec()),
            );
        }
    }

    /// Sets all values in this multivar to the provided one without owning the
    /// provided input. Note that this requires `input` to last longer than
    /// [`GitConfig`]. Consider using [`Self::set_owned_values_all`] or
    /// [`Self::set_str_all`] unless you have a strict performance or memory
    /// need for a more ergonomic interface.
    ///
    /// [`GitConfig`]: super::GitConfig
    #[inline]
    pub fn set_values_all<'a: 'event>(&mut self, input: &'a [u8]) {
        for EntryData {
            section_id,
            offset_index,
        } in &self.indices_and_sizes
        {
            Self::set_value_inner(
                &self.key,
                &mut self.offsets,
                self.section
                    .get_mut(section_id)
                    .expect("sections does not have section id from section ids"),
                *section_id,
                *offset_index,
                Cow::Borrowed(input),
            );
        }
    }

    fn set_value_inner<'a: 'event>(
        key: &Key<'lookup>,
        offsets: &mut HashMap<SectionId, Vec<usize>>,
        section: &mut SectionBody<'event>,
        section_id: SectionId,
        offset_index: usize,
        input: Cow<'a, [u8]>,
    ) {
        let (offset, size) = MutableMultiValue::get_index_and_size(offsets, section_id, offset_index);
        section.as_mut().drain(offset..offset + size);

        MutableMultiValue::set_offset(offsets, section_id, offset_index, 3);
        section.as_mut().insert(offset, Event::Value(input));
        section.as_mut().insert(offset, Event::KeyValueSeparator);
        section
            .as_mut()
            .insert(offset, Event::Key(Key(Cow::Owned(key.0.to_string()))));
    }

    /// Removes the value at the given index. Does nothing when called multiple
    /// times in succession.
    ///
    /// # Safety
    ///
    /// This will panic if the index is out of range.
    pub fn delete(&mut self, index: usize) {
        let EntryData {
            section_id,
            offset_index,
        } = &self.indices_and_sizes[index];
        let (offset, size) = MutableMultiValue::get_index_and_size(&self.offsets, *section_id, *offset_index);
        if size > 0 {
            self.section
                .get_mut(section_id)
                .expect("sections does not have section id from section ids")
                .as_mut()
                .drain(offset..offset + size);

            Self::set_offset(&mut self.offsets, *section_id, *offset_index, 0);
            self.indices_and_sizes.remove(index);
        }
    }

    /// Removes all values. Does nothing when called multiple times in
    /// succession.
    pub fn delete_all(&mut self) {
        for EntryData {
            section_id,
            offset_index,
        } in &self.indices_and_sizes
        {
            let (offset, size) = MutableMultiValue::get_index_and_size(&self.offsets, *section_id, *offset_index);
            if size > 0 {
                self.section
                    .get_mut(section_id)
                    .expect("sections does not have section id from section ids")
                    .as_mut()
                    .drain(offset..offset + size);
                Self::set_offset(&mut self.offsets, *section_id, *offset_index, 0);
            }
        }
        self.indices_and_sizes.clear();
    }

    // SectionId is the same size as a reference, which means it's just as
    // efficient passing in a value instead of a reference.
    #[inline]
    fn get_index_and_size(
        offsets: &'lookup HashMap<SectionId, Vec<usize>>,
        section_id: SectionId,
        offset_index: usize,
    ) -> (usize, usize) {
        offsets
            .get(&section_id)
            .expect("sections does not have section id from section ids")
            .iter()
            .take(offset_index + 1)
            .fold((0, 0), |(old, new), offset| (old + new, *offset))
    }

    // This must be an associated function rather than a method to allow Rust
    // to split mutable borrows.
    //
    // SectionId is the same size as a reference, which means it's just as
    // efficient passing in a value instead of a reference.
    #[inline]
    fn set_offset(
        offsets: &mut HashMap<SectionId, Vec<usize>>,
        section_id: SectionId,
        offset_index: usize,
        value: usize,
    ) {
        *offsets
            .get_mut(&section_id)
            .expect("sections does not have section id from section ids")
            .get_mut(offset_index)
            .unwrap()
            .deref_mut() = value;
    }
}