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
use std::sync::Arc;
use std::fmt;

use Variable;

// Do not change this without updating the algorithms!
const BLOCK_SIZE: usize = 124;

const EMPTY: u64 = 0x0;
const BOOL: u64 = 0x1;
const F64: u64 = 0x2;
const STR: u64 = 0x3;

/// Stores link memory in chunks of 1024 bytes.
pub struct Block {
    data: [u64; BLOCK_SIZE],
    tys: [u64; 4]
}

impl Block {
    pub fn new() -> Block {
        Block {
            data: [0; BLOCK_SIZE],
            tys: [0; 4],
        }
    }

    pub fn var(&self, ind: u8) -> Variable {
        use std::mem::transmute;

        let k = ind as usize;
        assert!(k < BLOCK_SIZE);
        let i = k / 32;
        let j = k - i * 32;
        match self.tys[i] >> (j * 2) & 0x3 {
            EMPTY => panic!("Reading beyond end"),
            BOOL => Variable::bool(self.data[k] != 0),
            F64 => {
                Variable::f64(unsafe {
                    transmute::<u64, f64>(self.data[k])
                })
            }
            STR => {

                Variable::Text(unsafe {
                    transmute::<&u64, &Arc<String>>(&self.data[k])
                }.clone())
            }
            _ => panic!("Invalid type"),
        }
    }

    pub fn push(&mut self, var: &Variable, pos: usize) {
        use std::mem::transmute;

        let k = pos;
        assert!(k < BLOCK_SIZE);

        let i = k / 32;
        let j = k - i * 32;
        match *var {
            Variable::Bool(val, _) => {
                // Reset bits.
                self.tys[i] &= !(0x3 << (j * 2));
                // Sets new bits.
                self.tys[i] |= BOOL << (j * 2);
                self.data[k] = val as u64;
            }
            Variable::F64(val, _) => {
                // Reset bits.
                self.tys[i] &= !(0x3 << (j * 2));
                // Sets new bits.
                self.tys[i] |= F64 << (j * 2);
                self.data[k] = unsafe { transmute::<f64, u64>(val) };
            }
            Variable::Text(ref s) => {
                // Reset bits.
                self.tys[i] &= !(0x3 << (j * 2));
                // Sets new bits.
                self.tys[i] |= STR << (j * 2);
                self.data[k] = unsafe { transmute::<Arc<String>, usize>(s.clone()) as u64 };
            }
            _ => panic!("Expected `str`, `f64`, `bool`")
        }
    }
}

impl Clone for Block {
    fn clone(&self) -> Block {
        use std::mem::transmute;

        let mut data = self.data;
        for k in 0..BLOCK_SIZE {
            let i = k / 32;
            let j = k - i * 32;
            match self.tys[i] >> (j * 2) & 0x3 {
                EMPTY => break,
                STR => {
                    // Arc<String>
                    unsafe {
                        data[k] = transmute::<Arc<String>, usize>(
                            transmute::<&usize, &Arc<String>>(
                                &(self.data[k] as usize)
                            ).clone()) as u64;
                    }
                }
                _ => {}
            }
        }
        Block {
            data: data,
            tys: self.tys,
        }
    }
}

impl Drop for Block {
    fn drop(&mut self) {
        use std::mem::transmute;

        for k in 0..BLOCK_SIZE {
            let i = k / 32;
            let j = k - i * 32;
            match self.tys[i] >> (j * 2) & 0x3 {
                EMPTY => break,
                STR => {
                    // Arc<String>
                    unsafe {
                        drop(transmute::<usize, Arc<String>>(self.data[k] as usize))
                    }
                }
                _ => {}
            }
        }
    }
}

impl fmt::Debug for Block {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Block")
    }
}

#[derive(Debug, Clone)]
pub struct Slice {
    pub block: Arc<Block>,
    pub start: u8,
    pub end: u8,
}

impl Slice {
    pub fn new() -> Slice {
        Slice {
            block: Arc::new(Block::new()),
            start: 0,
            end: 0,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Link {
    pub slices: Vec<Slice>,
}

impl Link {
    pub fn new() -> Link {
        Link {
            slices: vec![]
        }
    }

    pub fn head(&self) -> Option<Box<Variable>> {
        if self.slices.len() == 0 { None }
        else {
            let first = &self.slices[0];
            if first.start < first.end {
                Some(Box::new(first.block.var(first.start)))
            } else {
                None
            }
        }
    }

    pub fn tip(&self) -> Option<Box<Variable>> {
        if let Some(last) = self.slices.last() {
            if last.start < last.end {
                Some(Box::new(last.block.var(last.end - 1)))
            } else {
                None
            }
        } else { None }
    }

    pub fn tail(&self) -> Link {
        if self.slices.len() == 0 { Link::new() }
        else {
            let first = &self.slices[0];
            let mut l = Link::new();
            // No danger of overflow since `BLOCK_SIZE = 124`.
            if first.start + 1 < first.end {
                l.slices.push(first.clone());
                l.slices[0].start += 1;
            }
            for slice in self.slices.iter().skip(1) {
                l.slices.push(slice.clone())
            }
            l
        }
    }

    pub fn neck(&self) -> Link {
        if let Some(last) = self.slices.last() {
            let mut l = Link::new();
            for slice in self.slices.iter().take(self.slices.len() - 1) {
                l.slices.push(slice.clone())
            }
            // No danger of overflow since `BLOCK_SIZE = 124`.
            if last.start + 1 < last.end {
                l.slices.push(Slice {
                    block: last.block.clone(),
                    start: last.start,
                    end: last.end - 1
                })
            }
            l
        } else { Link::new() }
    }

    pub fn is_empty(&self) -> bool { self.slices.len() == 0 }

    pub fn add(&self, other: &Link) -> Link {
        let mut slices = Vec::with_capacity(self.slices.len() + other.slices.len());
        slices.extend_from_slice(&self.slices);
        slices.extend_from_slice(&other.slices);
        Link {
            slices: slices
        }
    }

    pub fn push(&mut self, v: &Variable) -> Result<(), String> {
        match v {
            &Variable::Bool(_, _) |
            &Variable::F64(_, _) |
            &Variable::Text(_) => {
                if self.slices.len() > 0 {
                    let mut last = self.slices.last_mut().unwrap();
                    if (last.end as usize) < BLOCK_SIZE {
                        Arc::make_mut(&mut last.block).push(v, last.end as usize);
                        last.end += 1;
                        return Ok(());
                    }
                }

                self.slices.push(Slice::new());
                let mut last = self.slices.last_mut().unwrap();
                Arc::make_mut(&mut last.block).push(v, 0);
                last.end = 1;
                Ok(())
            }
            &Variable::Link(ref link) => {
                for slice in &link.slices {
                    for i in slice.start..slice.end {
                        try!(self.push(&slice.block.var(i)))
                    }
                }
                Ok(())
            }
            _ => return Err("Expected `bool`, `f64` or `str`".into())
        }
    }
}