editable 0.1.0

Editing history utility for editors
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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use std::{
    error::Error,
    marker::PhantomData,
    sync::{Arc, RwLock},
};

/// An error that can occur during editing operations.
#[derive(Debug)]
pub enum EditableError {
    /// An error indicating that an action cannot be performed.
    CannotDoAction(String),
    /// An error indicating that an action cannot be undone.
    CannotUndoAction(String),
    /// A custom error.
    Custom(Box<dyn Error>),
}

impl std::fmt::Display for EditableError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CannotDoAction(desc) => write!(f, "Cannot do action: {}", desc),
            Self::CannotUndoAction(desc) => write!(f, "Cannot undo action: {}", desc),
            Self::Custom(error) => write!(f, "Custom error: {}", error),
        }
    }
}

impl Error for EditableError {}

/// A trait representing an action that can be performed on editable data.
/// It provides methods to execute and undo the action.
pub trait EditAction<T> {
    /// Executes the action on the given data.
    ///
    /// # Arguments
    /// * `data` - A mutable reference to the data on which the action is performed.
    ///
    /// # Returns
    /// A result indicating success or failure.
    fn execute(&mut self, data: &mut T) -> Result<(), EditableError>;

    /// Undoes the action on the given data.
    ///
    /// # Arguments
    /// * `data` - A mutable reference to the data on which the action is undone.
    ///
    /// # Returns
    /// A result indicating success or failure.
    fn undo(&mut self, data: &mut T) -> Result<(), EditableError>;
}

/// An action that takes a snapshot of the data before executing.
/// If the action fails, it restores the data to its previous state.
/// Mostly useful for clonable data types. On undo it restores the data
/// to the state before the action was executed.
///
/// # Type Parameters
/// * `T` - The type of data being edited.
/// * `E` - The type of closure that defines the action to be executed.
pub struct SnapshotEditAction<T, E>
where
    T: Clone,
    E: FnMut(&mut T) -> Result<(), EditableError>,
{
    state: Option<T>,
    execute: E,
}

impl<T, E> SnapshotEditAction<T, E>
where
    T: Clone,
    E: FnMut(&mut T) -> Result<(), EditableError>,
{
    /// Creates a new `SnapshotEditAction`.
    ///
    /// # Arguments
    /// * `execute` - A closure that defines the action to be executed.
    ///
    /// # Returns
    /// A new instance of `SnapshotEditAction`.
    pub fn new(execute: E) -> Self {
        Self {
            state: None,
            execute,
        }
    }
}

impl<T, E> EditAction<T> for SnapshotEditAction<T, E>
where
    T: Clone,
    E: FnMut(&mut T) -> Result<(), EditableError>,
{
    fn execute(&mut self, data: &mut T) -> Result<(), EditableError> {
        let state = self.state.replace(data.clone());
        match (self.execute)(data) {
            Ok(_) => Ok(()),
            Err(error) => {
                self.state = state;
                Err(error)
            }
        }
    }

    fn undo(&mut self, data: &mut T) -> Result<(), EditableError> {
        if let Some(state) = self.state.take() {
            *data = state;
            Ok(())
        } else {
            Err(EditableError::Custom(
                "Could not undo from snapshot!".into(),
            ))
        }
    }
}

/// An action that executes a closure to modify the data.
/// It can also undo the action by executing another closure.
///
/// # Type Parameters
/// * `T` - The type of data being edited.
/// * `S` - The type of state used by the closures.
/// * `E` - The type of closure that defines the action to be executed.
/// * `U` - The type of closure that defines the action to undo the executed action.
pub struct ClosureEditAction<T, S, E, U>
where
    E: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
    U: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
{
    state: S,
    execute: E,
    undo: U,
    _phantom: PhantomData<fn() -> T>,
}

impl<T, S, E, U> ClosureEditAction<T, S, E, U>
where
    E: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
    U: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
{
    /// Creates a new `ClosureEditAction`.
    ///
    /// # Arguments
    /// * `execute` - A closure that defines the action to be executed.
    /// * `undo` - A closure that defines the action to undo the executed action.
    /// * `state` - The state used by the closures.
    ///
    /// # Returns
    /// A new instance of `ClosureEditAction`.
    pub fn new(execute: E, undo: U, state: S) -> Self {
        Self {
            state,
            execute,
            undo,
            _phantom: Default::default(),
        }
    }
}

impl<T, S, E, U> EditAction<T> for ClosureEditAction<T, S, E, U>
where
    E: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
    U: FnMut(&mut T, &mut S) -> Result<(), EditableError>,
{
    fn execute(&mut self, data: &mut T) -> Result<(), EditableError> {
        (self.execute)(data, &mut self.state)
    }

    fn undo(&mut self, data: &mut T) -> Result<(), EditableError> {
        (self.undo)(data, &mut self.state)
    }
}

/// A record of an edit action.
/// It contains a description of the action and a reference to the action itself.
/// Useful for editor history with descriptive names of edit actions.
///
/// # Type Parameters
/// * `T` - The type of data being edited.
#[derive(Clone)]
struct EditRecord<T> {
    description: String,
    action: Arc<RwLock<dyn EditAction<T>>>,
}

impl<T> EditAction<T> for EditRecord<T> {
    fn execute(&mut self, data: &mut T) -> Result<(), EditableError> {
        if let Ok(mut action) = self.action.try_write() {
            action.execute(data)
        } else {
            Err(EditableError::CannotDoAction(self.description.to_owned()))
        }
    }

    fn undo(&mut self, data: &mut T) -> Result<(), EditableError> {
        if let Ok(mut action) = self.action.try_write() {
            action.undo(data)
        } else {
            Err(EditableError::CannotUndoAction(self.description.to_owned()))
        }
    }
}

impl<T> std::fmt::Debug for EditRecord<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(&format!("EditAction<{}>", std::any::type_name::<T>()))
            .field("description", &self.description)
            .finish_non_exhaustive()
    }
}

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

/// An enum representing the kind of edit history.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditHistoryKind {
    /// Represents a completed edit action.
    Done,
    /// Represents an undone edit action.
    Undone,
}

/// A struct representing an editable data structure.
/// It allows for editing, undoing, and redoing actions on the data.
/// It also maintains a history of actions performed on the data.
///
/// # Type Parameters
/// * `T` - The type of data being edited.
#[derive(Debug, Default, Clone)]
pub struct Editable<T> {
    data: T,
    done: Vec<EditRecord<T>>,
    undone: Vec<EditRecord<T>>,
    capacity: usize,
}

impl<T> Editable<T> {
    /// Creates a new `Editable` instance with the given data.
    ///
    /// # Arguments
    /// * `data` - The data to be edited.
    ///
    /// # Returns
    /// A new instance of `Editable`.
    pub fn new(data: T) -> Self {
        Self {
            data,
            done: Default::default(),
            undone: Default::default(),
            capacity: 0,
        }
    }

    /// Creates a new `Editable` instance with the given data and capacity.
    ///
    /// # Arguments
    /// * `data` - The data to be edited.
    /// * `capacity` - The maximum number of actions to keep in history.
    ///
    /// # Returns
    /// A new instance of `Editable`.
    pub fn with_capacity(mut self, capacity: usize) -> Self {
        self.set_capacity(capacity);
        self
    }

    /// Commits the changes made to the data and returns it.
    pub fn commit(self) -> T {
        self.data
    }

    /// Returns a reference to the data.
    pub fn data(&self) -> &T {
        &self.data
    }

    /// Returns history capacity.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Sets the history capacity.
    /// If the capacity is set to 0, the history will not be limited.
    /// If the capacity is set to a positive number, the history will be limited to that number.
    /// If the history exceeds the capacity, the oldest actions will be removed.
    ///
    /// # Arguments
    /// * `capacity` - The maximum number of actions to keep in history.
    pub fn set_capacity(&mut self, capacity: usize) {
        self.capacity = capacity;
        if self.capacity > 0 {
            self.clear_undone();
            while self.done.len() > self.capacity {
                self.done.remove(0);
            }
        }
    }

    /// Returns the number of actions in the done history.
    pub fn done_count(&self) -> usize {
        self.done.len()
    }

    /// Returns the number of actions in the undone history.
    pub fn undone_count(&self) -> usize {
        self.undone.len()
    }

    /// Clears the undone history.
    /// This will remove all actions from the undone history.
    /// The done history will not be affected.
    pub fn clear_undone(&mut self) {
        self.undone.clear();
    }

    /// Performs an edit action on the data.
    /// This will execute the action and add it to the done history.
    /// If the action fails, it will not be added to the history.
    /// The undone history will be cleared.
    ///
    /// # Arguments
    /// * `description` - A description of the action.
    /// * `action` - The action to be performed.
    pub fn edit(
        &mut self,
        description: impl ToString,
        action: impl EditAction<T> + 'static,
    ) -> Result<(), EditableError> {
        let mut record = EditRecord {
            description: description.to_string(),
            action: Arc::new(RwLock::new(action)),
        };
        record.execute(&mut self.data)?;
        self.undone.clear();
        self.done_push(record);
        Ok(())
    }

    /// Performs an edit action on the data with snapshots.
    ///
    /// # Arguments
    /// * `description` - A description of the action.
    /// * `execute` - A closure that defines the action to be executed.
    pub fn edit_snapshot<E>(
        &mut self,
        description: impl ToString,
        execute: E,
    ) -> Result<(), EditableError>
    where
        T: Clone + 'static,
        E: FnMut(&mut T) -> Result<(), EditableError> + 'static,
    {
        self.edit(description, SnapshotEditAction::<T, E>::new(execute))
    }

    /// Performs an edit action on the data with closures.
    ///
    /// # Arguments
    /// * `description` - A description of the action.
    /// * `execute` - A closure that defines the action to be executed.
    /// * `undo` - A closure that defines the action to undo the executed action.
    /// * `state` - The state used by the closures.
    pub fn edit_closure<S, E, U>(
        &mut self,
        description: impl ToString,
        execute: E,
        undo: U,
        state: S,
    ) -> Result<(), EditableError>
    where
        T: 'static,
        S: 'static,
        E: FnMut(&mut T, &mut S) -> Result<(), EditableError> + 'static,
        U: FnMut(&mut T, &mut S) -> Result<(), EditableError> + 'static,
    {
        self.edit(
            description,
            ClosureEditAction::<T, S, E, U>::new(execute, undo, state),
        )
    }

    /// Undoes last action in the done history.
    /// Undone action is added to the undone history.
    pub fn undo_last(&mut self) -> Result<(), EditableError> {
        if let Some(mut record) = self.done.pop() {
            if let Err(error) = record.undo(&mut self.data) {
                self.done_push(record);
                return Err(error);
            }
            self.undone.push(record);
        }
        Ok(())
    }

    /// Undoes last `count` number of actions in the done history.
    ///
    /// # Arguments
    /// * `count` - The number of actions to undo.
    pub fn undo_many(&mut self, mut count: usize) -> Result<(), EditableError> {
        count = count.min(self.done_count());
        while count > 0 {
            self.undo_last()?;
            count -= 1;
        }
        Ok(())
    }

    /// Undoes all actions in the done history.
    pub fn undo_all(&mut self) -> Result<(), EditableError> {
        while self.done_count() > 0 {
            self.undo_last()?;
        }
        Ok(())
    }

    /// Redoes last action in the undone history.
    /// Redone action is added to the done history.
    pub fn redo_last(&mut self) -> Result<(), EditableError> {
        if let Some(mut record) = self.undone.pop() {
            if let Err(error) = record.execute(&mut self.data) {
                self.undone.push(record);
                return Err(error);
            }
            self.done_push(record);
        }
        Ok(())
    }

    /// Redoes last `count` number of actions in the undone history.
    ///
    /// # Arguments
    /// * `count` - The number of actions to redo.
    pub fn redo_many(&mut self, mut count: usize) -> Result<(), EditableError> {
        count = count.min(self.undone_count());
        while count > 0 {
            self.redo_last()?;
            count -= 1;
        }
        Ok(())
    }

    /// Redoes all actions in the undone history.
    pub fn redo_all(&mut self) -> Result<(), EditableError> {
        while self.undone_count() > 0 {
            self.redo_last()?;
        }
        Ok(())
    }

    /// Returns an iterator over the history of actions.
    /// The iterator yields tuples containing the description of the action,
    /// the kind of action (done or undone), and the index of the action.
    pub fn history(&self) -> impl Iterator<Item = (&str, EditHistoryKind, usize)> + '_ {
        let done_count = self.done.len();
        let undone_count = self.undone.len();
        self.done
            .iter()
            .enumerate()
            .map(move |(index, action)| {
                (
                    action.description.as_str(),
                    EditHistoryKind::Done,
                    done_count - index,
                )
            })
            .chain(
                self.undone
                    .iter()
                    .enumerate()
                    .rev()
                    .map(move |(index, action)| {
                        (
                            action.description.as_str(),
                            EditHistoryKind::Undone,
                            undone_count - index,
                        )
                    }),
            )
    }

    fn done_push(&mut self, record: EditRecord<T>) {
        self.done.push(record);
        if self.capacity > 0 {
            while self.done.len() > self.capacity {
                self.done.remove(0);
            }
        }
    }
}

/// A struct representing a possibly editable data.
/// It can either be fixed or editable.
pub enum PossiblyEditable<T> {
    /// Represents fixed data that cannot be edited.
    Fixed(T),
    /// Represents editable data that can be modified.
    /// It contains an `Editable` instance that manages the editing process.
    Editable(Editable<T>),
}

impl<T> PossiblyEditable<T> {
    /// Creates a new `PossiblyEditable` instance with fixed data.
    ///
    /// # Arguments
    /// * `data` - The fixed data.
    ///
    /// # Returns
    /// A new instance of `PossiblyEditable`.
    pub fn new(data: T) -> Self {
        Self::Fixed(data)
    }

    /// Tells if the data is fixed.
    pub fn is_fixed(&self) -> bool {
        matches!(self, Self::Fixed(_))
    }

    /// Tells if the data is editable.
    pub fn is_editable(&self) -> bool {
        matches!(self, Self::Editable(_))
    }

    /// Consumes data and returns it.
    pub fn into_data(self) -> T {
        match self {
            Self::Fixed(data) => data,
            Self::Editable(editable) => editable.commit(),
        }
    }

    /// Turns possibly fixed data into editable data.
    pub fn turn_editable(&mut self) {
        unsafe {
            let ptr = self as *mut Self;
            let data = match ptr.read() {
                Self::Fixed(data) => Self::Editable(Editable::new(data)),
                data => data,
            };
            ptr.write(data);
        }
    }

    /// Turns possibly editable data into fixed data.
    pub fn turn_fixed(&mut self) {
        unsafe {
            let ptr = self as *mut Self;
            let data = match ptr.read() {
                Self::Editable(data) => Self::Fixed(data.commit()),
                data => data,
            };
            ptr.write(data);
        }
    }

    /// Returns a reference to the data if it is fixed.
    pub fn as_fixed(&self) -> Option<&T> {
        match self {
            Self::Fixed(data) => Some(data),
            _ => None,
        }
    }

    /// Returns a mutable reference to the data if it is fixed.
    pub fn as_fixed_mut(&mut self) -> Option<&mut T> {
        match self {
            Self::Fixed(data) => Some(data),
            _ => None,
        }
    }

    /// Returns a reference to the editable instance if it is editable.
    pub fn as_editable(&self) -> Option<&Editable<T>> {
        match self {
            Self::Editable(data) => Some(data),
            _ => None,
        }
    }

    /// Returns a mutable reference to the editable instance if it is editable.
    pub fn as_editable_mut(&mut self) -> Option<&mut Editable<T>> {
        match self {
            Self::Editable(data) => Some(data),
            _ => None,
        }
    }
}

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

    #[test]
    fn test_editable() {
        let mut editable = Editable::new(0usize);
        assert_eq!(editable.done_count(), 0);
        assert_eq!(editable.undone_count(), 0);

        editable
            .edit_snapshot("set 42", |data| {
                *data = 42;
                Ok(())
            })
            .unwrap();
        assert_eq!(editable.done_count(), 1);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 42);

        editable.undo_last().unwrap();
        assert_eq!(editable.done_count(), 0);
        assert_eq!(editable.undone_count(), 1);
        assert_eq!(*editable.data(), 0);

        editable.redo_last().unwrap();
        assert_eq!(editable.done_count(), 1);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 42);

        editable
            .edit_snapshot("add 8", |data| {
                *data += 8;
                Ok(())
            })
            .unwrap();
        assert_eq!(editable.done_count(), 2);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 50);

        editable
            .edit_snapshot("div 5", |data| {
                *data /= 5;
                Ok(())
            })
            .unwrap();
        assert_eq!(editable.done_count(), 3);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 10);

        editable.undo_many(2).unwrap();
        assert_eq!(editable.done_count(), 1);
        assert_eq!(editable.undone_count(), 2);
        assert_eq!(*editable.data(), 42);

        editable.redo_all().unwrap();
        assert_eq!(editable.done_count(), 3);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 10);

        editable.undo_last().unwrap();
        assert_eq!(
            editable.history().collect::<Vec<_>>(),
            vec![
                ("set 42", EditHistoryKind::Done, 2),
                ("add 8", EditHistoryKind::Done, 1),
                ("div 5", EditHistoryKind::Undone, 1)
            ]
        );

        editable
            .edit_snapshot("mul 2", |data| {
                *data *= 2;
                Ok(())
            })
            .unwrap();
        assert_eq!(editable.done_count(), 3);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 100);

        editable.set_capacity(2);
        assert_eq!(editable.done_count(), 2);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(*editable.data(), 100);

        editable.undo_all().unwrap();
        editable.clear_undone();
        assert_eq!(editable.done_count(), 0);
        assert_eq!(editable.undone_count(), 0);
        assert_eq!(editable.commit(), 42);
    }
}