liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
Documentation
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
//! Character-level draft buffer with rollback support.
//!
//! This module implements a buffer for tracking tentative text input with
//! efficient character-level insertion and deletion (backspace) operations.

use std::collections::VecDeque;

/// Buffer for managing draft text with character-level operations.
///
/// DraftBuffer uses a VecDeque to enable O(1) push/pop operations on both
/// ends, making it efficient for both forward typing and backspace operations.
///
/// # Memory Efficiency
///
/// - Small allocations: ~24 bytes base + character storage
/// - VecDeque growth: 2x when capacity exceeded (amortized O(1))
/// - No allocations for backspace (just decrements length)
///
/// # Use Cases
///
/// - Code editor: Track partial identifier as user types
/// - Autocomplete: Build query string incrementally
/// - Undo/redo: Checkpoint and restore buffer state
///
/// # Examples
///
/// ```
/// use liblevenshtein::contextual::DraftBuffer;
///
/// let mut buffer = DraftBuffer::new();
///
/// // User types "he"
/// buffer.insert('h');
/// buffer.insert('e');
/// assert_eq!(buffer.as_str(), "he");
///
/// // User types "l"
/// buffer.insert('l');
/// assert_eq!(buffer.as_str(), "hel");
///
/// // User hits backspace
/// assert_eq!(buffer.delete(), Some('l'));
/// assert_eq!(buffer.as_str(), "he");
/// ```
#[derive(Debug, Clone)]
pub struct DraftBuffer {
    /// Character storage (VecDeque for efficient push/pop on both ends)
    chars: VecDeque<char>,
}

impl DraftBuffer {
    /// Create a new empty draft buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::new();
    /// assert_eq!(buffer.len(), 0);
    /// assert!(buffer.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            chars: VecDeque::new(),
        }
    }

    /// Create a draft buffer with the given initial capacity.
    ///
    /// This avoids reallocation if you know the approximate size.
    ///
    /// # Arguments
    ///
    /// * `capacity` - Initial capacity in characters
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// // Preallocate for typical identifier length
    /// let buffer = DraftBuffer::with_capacity(32);
    /// assert!(buffer.is_empty());
    /// ```
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            chars: VecDeque::with_capacity(capacity),
        }
    }

    /// Create a draft buffer from an existing string.
    ///
    /// # Arguments
    ///
    /// * `s` - Initial string content
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::from_string("hello");
    /// assert_eq!(buffer.as_str(), "hello");
    /// assert_eq!(buffer.len(), 5);
    /// ```
    pub fn from_string(s: &str) -> Self {
        let chars: VecDeque<char> = s.chars().collect();
        Self { chars }
    }

    /// Insert a character at the end of the buffer.
    ///
    /// # Arguments
    ///
    /// * `ch` - Character to insert
    ///
    /// # Performance
    ///
    /// O(1) amortized. May trigger reallocation if capacity exceeded.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let mut buffer = DraftBuffer::new();
    /// buffer.insert('a');
    /// buffer.insert('b');
    /// assert_eq!(buffer.as_str(), "ab");
    /// ```
    pub fn insert(&mut self, ch: char) {
        self.chars.push_back(ch);
    }

    /// Delete the last character from the buffer (backspace).
    ///
    /// # Returns
    ///
    /// `Some(ch)` if a character was deleted, `None` if buffer was empty.
    ///
    /// # Performance
    ///
    /// O(1). No allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let mut buffer = DraftBuffer::from_string("test");
    /// assert_eq!(buffer.delete(), Some('t'));
    /// assert_eq!(buffer.delete(), Some('s'));
    /// assert_eq!(buffer.as_str(), "te");
    /// assert_eq!(buffer.len(), 2);
    /// ```
    pub fn delete(&mut self) -> Option<char> {
        self.chars.pop_back()
    }

    /// Get the buffer length in characters.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::from_string("hello");
    /// assert_eq!(buffer.len(), 5);
    /// ```
    pub fn len(&self) -> usize {
        self.chars.len()
    }

    /// Check if the buffer is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::new();
    /// assert!(buffer.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.chars.is_empty()
    }

    /// Get the buffer content as a string slice.
    ///
    /// # Performance
    ///
    /// O(n) allocation to collect characters into a String.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::from_string("test");
    /// assert_eq!(buffer.as_str(), "test");
    /// ```
    pub fn as_str(&self) -> String {
        self.chars.iter().collect()
    }

    /// Get the buffer content as a byte vector (UTF-8).
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let buffer = DraftBuffer::from_string("test");
    /// assert_eq!(buffer.as_bytes(), b"test");
    /// ```
    pub fn as_bytes(&self) -> Vec<u8> {
        self.as_str().into_bytes()
    }

    /// Clear all content from the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let mut buffer = DraftBuffer::from_string("test");
    /// buffer.clear();
    /// assert!(buffer.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.chars.clear();
    }

    /// Truncate the buffer to the specified length.
    ///
    /// If `len` is greater than the current length, this has no effect.
    ///
    /// # Arguments
    ///
    /// * `len` - Target length in characters
    ///
    /// # Examples
    ///
    /// ```
    /// use liblevenshtein::contextual::DraftBuffer;
    ///
    /// let mut buffer = DraftBuffer::from_string("hello");
    /// buffer.truncate(3);
    /// assert_eq!(buffer.as_str(), "hel");
    /// ```
    pub fn truncate(&mut self, len: usize) {
        if len < self.chars.len() {
            self.chars.truncate(len);
        }
    }
}

impl Default for DraftBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl From<String> for DraftBuffer {
    fn from(s: String) -> Self {
        Self::from_string(&s)
    }
}

impl From<&str> for DraftBuffer {
    fn from(s: &str) -> Self {
        Self::from_string(s)
    }
}

impl std::fmt::Display for DraftBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new() {
        let buffer = DraftBuffer::new();
        assert_eq!(buffer.len(), 0);
        assert!(buffer.is_empty());
        assert_eq!(buffer.as_str(), "");
    }

    #[test]
    fn test_insert() {
        let mut buffer = DraftBuffer::new();
        buffer.insert('a');
        buffer.insert('b');
        buffer.insert('c');
        assert_eq!(buffer.len(), 3);
        assert_eq!(buffer.as_str(), "abc");
    }

    #[test]
    fn test_delete() {
        let mut buffer = DraftBuffer::from_string("test");
        assert_eq!(buffer.delete(), Some('t'));
        assert_eq!(buffer.as_str(), "tes");
        assert_eq!(buffer.delete(), Some('s'));
        assert_eq!(buffer.as_str(), "te");
        assert_eq!(buffer.len(), 2);
    }

    #[test]
    fn test_delete_empty() {
        let mut buffer = DraftBuffer::new();
        assert_eq!(buffer.delete(), None);
    }

    #[test]
    fn test_from_str() {
        let buffer = DraftBuffer::from_string("hello");
        assert_eq!(buffer.len(), 5);
        assert_eq!(buffer.as_str(), "hello");
    }

    #[test]
    fn test_clear() {
        let mut buffer = DraftBuffer::from_string("test");
        buffer.clear();
        assert!(buffer.is_empty());
        assert_eq!(buffer.as_str(), "");
    }

    #[test]
    fn test_truncate() {
        let mut buffer = DraftBuffer::from_string("hello");
        buffer.truncate(3);
        assert_eq!(buffer.as_str(), "hel");
        assert_eq!(buffer.len(), 3);
    }

    #[test]
    fn test_truncate_longer() {
        let mut buffer = DraftBuffer::from_string("hi");
        buffer.truncate(10);
        assert_eq!(buffer.as_str(), "hi");
        assert_eq!(buffer.len(), 2);
    }

    #[test]
    fn test_unicode() {
        let mut buffer = DraftBuffer::new();
        buffer.insert('πŸ˜€');
        buffer.insert('δΈ–');
        buffer.insert('η•Œ');
        assert_eq!(buffer.len(), 3);
        assert_eq!(buffer.as_str(), "πŸ˜€δΈ–η•Œ");
        assert_eq!(buffer.delete(), Some('η•Œ'));
        assert_eq!(buffer.as_str(), "πŸ˜€δΈ–");
    }

    #[test]
    fn test_as_bytes() {
        let buffer = DraftBuffer::from_string("test");
        assert_eq!(buffer.as_bytes(), b"test");
    }

    #[test]
    fn test_display() {
        let buffer = DraftBuffer::from_string("test");
        assert_eq!(format!("{}", buffer), "test");
    }

    #[test]
    fn test_from_string() {
        let buffer = DraftBuffer::from(String::from("hello"));
        assert_eq!(buffer.as_str(), "hello");
    }

    #[test]
    fn test_with_capacity() {
        let buffer = DraftBuffer::with_capacity(100);
        assert!(buffer.is_empty());
    }

    #[test]
    fn test_incremental_typing() {
        let mut buffer = DraftBuffer::new();

        // Simulate typing "hello"
        for ch in "hello".chars() {
            buffer.insert(ch);
        }
        assert_eq!(buffer.as_str(), "hello");

        // Simulate backspace twice
        buffer.delete();
        buffer.delete();
        assert_eq!(buffer.as_str(), "hel");

        // Continue typing "p"
        buffer.insert('p');
        assert_eq!(buffer.as_str(), "help");
    }
}