pcp/variable/memory/trail/
single_value_trail.rs

1// Copyright 2016 Pierre Talbot (IRCAM)
2
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6
7//     http://www.apache.org/licenses/LICENSE-2.0
8
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use variable::memory::trail::memory_cell::MemoryCell;
16
17use variable::memory::ops::*;
18use gcollections::ops::*;
19use gcollections::kind::*;
20use std::fmt::{Formatter, Display, Error};
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct SingleValueTrail<Domain>
24{
25  trail: Vec<MemoryCell<Domain>>
26}
27
28impl<Domain> Collection for SingleValueTrail<Domain>
29{
30  type Item = Domain;
31}
32
33impl<Domain> AssociativeCollection for SingleValueTrail<Domain>
34{
35  type Location = usize;
36}
37
38impl<Domain> TrailVariable for SingleValueTrail<Domain>
39{
40  fn trail_variable(&mut self, loc: usize, value: Domain) {
41    self.trail.push(MemoryCell::new(loc, value))
42  }
43}
44
45impl<Domain> TrailRestoration for SingleValueTrail<Domain>
46{
47  type Mark = usize;
48
49  fn mark(&mut self) -> Self::Mark {
50    self.trail.len()
51  }
52
53  fn undo(&mut self, mark: Self::Mark, memory: &mut Vec<Domain>) {
54    while self.trail.len() != mark {
55      let cell = self.trail.pop().unwrap();
56      memory[cell.location] = cell.value;
57    }
58  }
59}
60
61impl<Domain> Display for SingleValueTrail<Domain> where
62 Domain: Display
63{
64  fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {
65    for cell in &self.trail {
66      formatter.write_str(format!("{}\n", cell).as_str())?;
67    }
68    Ok(())
69  }
70}
71
72impl<Domain> Empty for SingleValueTrail<Domain>
73{
74  fn empty() -> SingleValueTrail<Domain> {
75    SingleValueTrail {
76      trail: vec![]
77    }
78  }
79}