ted 0.7.0

Core text editor functionality.
Documentation
/// If an Undo's Undo is itself an Undo,
/// its undo() must produce the initial Undo. :P
pub trait Undo {
    type Undo;

    fn undo(&self) -> Self::Undo;
}

pub struct History<T: Undo> {
    events: Vec<T>,
    len: usize
}

impl<T: Undo> History<T> {
    pub fn new() -> Self {
        Self {
            events: Vec::new(),
            len: 0
        }
    }

    pub fn len(&self) -> usize {
        self.len
    }

    pub fn undone(&self) -> usize {
        self.events.len().saturating_sub(self.len)
    }

    pub fn record(&mut self, event: T) {
        self.events.truncate(self.len);
        self.events.push(event);
        self.len = self.events.len();
    }

    pub fn undo(&mut self) -> Result<T::Undo, ()> {
        if self.len > 0 {
            self.len -= 1;
            let undo = self.events[self.len].undo();
            Ok(undo)
        } else {
            Err(())
        }
    }
}

impl<T: Undo + Clone> History<T> {
    pub fn redo(&mut self) -> Result<T, ()> {
        if self.len < self.events.len() {
            let redo = self.events[self.len].clone();
            self.len += 1;
            Ok(redo)
        } else {
            Err(())
        }
    }
}

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

    /// Meaningless test event.
    #[derive(PartialEq, Clone)]
    enum Event {
        Forward,
        Backward
    }

    impl Undo for Event {
        type Undo = Event;

        fn undo(&self) -> Self::Undo {
            match *self {
                Event::Forward  => Event::Backward,
                Event::Backward => Event::Forward
            }
        }
    }

    #[test]
    fn main() {
        let mut hist = History::new();

        assert!(hist.undo().is_err());
        assert!(hist.redo().is_err());

        assert_eq!(0, hist.len());
        assert_eq!(0, hist.undone());

        hist.record(Event::Forward);

        assert_eq!(1, hist.len());
        assert_eq!(0, hist.undone());

        hist.record(Event::Backward);

        assert_eq!(2, hist.len());
        assert_eq!(0, hist.undone());

        assert!(match hist.undo() {
            Result::Ok(Event::Forward) => true,
            _                          => false
        });
        assert!(match hist.undo() {
            Result::Ok(Event::Backward) => true,
            _                           => false
        });
        assert!(hist.undo().is_err());

        assert!(match hist.redo() {
            Result::Ok(Event::Forward) => true,
            _                          => false
        });
        assert!(match hist.redo() {
            Result::Ok(Event::Backward) => true,
            _                           => false
        });
        assert!(hist.redo().is_err());
    }
}