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
//! Multi-dimensional arrays with per-dimension specifiable lower bounds
#![doc(html_root_url="https://sfackler.github.io/rust-postgres-array/doc")]

#[macro_use(to_sql_checked)]
extern crate postgres;
extern crate byteorder;

use std::mem;
use std::slice;

mod impls;

/// Information about a dimension of an array
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub struct DimensionInfo {
    /// The size of the dimension
    pub len: usize,
    /// The index of the first element of the dimension
    pub lower_bound: isize,
}

/// Specifies methods that can be performed on multi-dimensional arrays
pub trait Array<T> {
    /// Returns information about the dimensions of this array
    fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo];

    /// Slices into this array, returning an immutable view of a subarray.
    ///
    /// ## Failure
    ///
    /// Fails if the array is one-dimensional or the index is out of bounds.
    fn slice<'a>(&'a self, idx: isize) -> ArraySlice<'a, T>;

    /// Retrieves an immutable reference to a value in this array.
    ///
    ///
    /// ## Failure
    ///
    /// Fails if the array is multi-dimensional or the index is out of bounds.
    fn get<'a>(&'a self, idx: isize) -> &'a T;
}

/// Specifies methods that can be performed on mutable multi-dimensional arrays
pub trait MutableArray<T> : Array<T> {
    /// Slices into this array, returning a mutable view of a subarray.
    ///
    /// ## Failure
    ///
    /// Fails if the array is one-dimensional or the index is out of bounds.
    fn slice_mut<'a>(&'a mut self, idx: isize) -> MutArraySlice<'a, T>;

    /// Retrieves a mutable reference to a value in this array.
    ///
    ///
    /// ## Failure
    ///
    /// Fails if the array is multi-dimensional or the index is out of bounds.
    fn get_mut<'a>(&'a mut self, idx: isize) -> &'a mut T;
}

#[doc(hidden)]
trait InternalArray<T>: Array<T> {
    fn shift_idx(&self, idx: isize) -> usize {
        let shifted_idx = idx - self.dimension_info()[0].lower_bound;
        assert!(shifted_idx >= 0 &&
                    shifted_idx < self.dimension_info()[0].len as isize,
                "Out of bounds array access");
        shifted_idx as usize
    }

    fn raw_get<'a>(&'a self, idx: usize, size: usize) -> &'a T;
}

#[doc(hidden)]
trait InternalMutableArray<T>: MutableArray<T> {
    fn raw_get_mut<'a>(&'a mut self, idx: usize, size: usize) -> &'a mut T;
}

/// A multi-dimensional array
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ArrayBase<T> {
    info: Vec<DimensionInfo>,
    data: Vec<T>,
}

impl<T> ArrayBase<T> {
    /// Creates a new multi-dimensional array from its underlying components.
    ///
    /// The data array should be provided in the higher-dimensional equivalent
    /// of row-major order.
    ///
    /// ## Failure
    ///
    /// Fails if there are 0 dimensions or the number of elements provided does
    /// not match the number of elements specified.
    pub fn from_raw(data: Vec<T>, info: Vec<DimensionInfo>)
            -> ArrayBase<T> {
        assert!((data.is_empty() && info.is_empty()) ||
                data.len() == info.iter().fold(1, |acc, i| acc * i.len),
                "Size mismatch");
        ArrayBase {
            info: info,
            data: data,
        }
    }

    /// Creates a new one-dimensional array from a vector.
    pub fn from_vec(data: Vec<T>, lower_bound: isize) -> ArrayBase<T> {
        ArrayBase {
            info: vec!(DimensionInfo {
                len: data.len(),
                lower_bound: lower_bound
            }),
            data: data
        }
    }

    /// Wraps this array in a new dimension of size 1.
    ///
    /// For example the one-dimensional array `[1,2]` would turn into
    /// the two-dimensional array `[[1,2]]`.
    pub fn wrap(&mut self, lower_bound: isize) {
        self.info.insert(0, DimensionInfo {
            len: 1,
            lower_bound: lower_bound
        })
    }

    /// Takes ownership of another array, appending it to the top-level
    /// dimension of this array.
    ///
    /// The dimensions of the other array must have an identical shape to the
    /// dimensions of a slice of this array. This includes both the sizes of
    /// the dimensions as well as their lower bounds.
    ///
    /// For example, if `[3,4]` is pushed onto `[[1,2]]`, the result is
    /// `[[1,2],[3,4]]`.
    ///
    /// ## Failure
    ///
    /// Fails if the other array does not have dimensions identical to the
    /// dimensions of a slice of this array.
    pub fn push_move(&mut self, other: ArrayBase<T>) {
        assert!(self.info.len() - 1 == other.info.len(),
                "Cannot append differently shaped arrays");
        for (info1, info2) in self.info.iter().skip(1).zip(other.info.iter()) {
            assert!(info1 == info2, "Cannot join differently shaped arrays");
        }
        self.info[0].len += 1;
        self.data.extend(other.data.into_iter());
    }

    /// Returns an iterator over the values in this array, in the
    /// higher-dimensional equivalent of row-major order.
    pub fn values<'a>(&'a self) -> slice::Iter<'a, T> {
        self.data.iter()
    }
}

impl<T> Array<T> for ArrayBase<T> {
    fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo] {
        &*self.info
    }

    fn slice<'a>(&'a self, idx: isize) -> ArraySlice<'a, T> {
        assert!(self.info.len() != 1,
                "Attempted to slice a one-dimensional array");
        ArraySlice {
            parent: ArrayParent::Base(self),
            idx: self.shift_idx(idx),
        }
    }

    fn get<'a>(&'a self, idx: isize) -> &'a T {
        assert!(self.info.len() == 1,
                "Attempted to get from a multi-dimensional array");
        self.raw_get(self.shift_idx(idx), 1)
    }
}

impl<T> MutableArray<T> for ArrayBase<T> {
    fn slice_mut<'a>(&'a mut self, idx: isize) -> MutArraySlice<'a, T> {
        assert!(self.info.len() != 1,
                "Attempted to slice_mut into a one-dimensional array");
        MutArraySlice {
            idx: self.shift_idx(idx),
            parent: MutArrayParent::Base(self),
        }
    }

    fn get_mut<'a>(&'a mut self, idx: isize) -> &'a mut T {
        assert!(self.info.len() == 1,
                "Attempted to get_mut from a multi-dimensional array");
        let idx = self.shift_idx(idx);
        self.raw_get_mut(idx, 1)
    }
}

impl<T> InternalArray<T> for ArrayBase<T> {
    fn raw_get<'a>(&'a self, idx: usize, _size: usize) -> &'a T {
        &self.data[idx]
    }
}

impl<T> InternalMutableArray<T> for ArrayBase<T> {
    fn raw_get_mut<'a>(&'a mut self, idx: usize, _size: usize) -> &'a mut T {
        &mut self.data[idx]
    }
}

enum ArrayParent<'parent, T:'static> {
    Slice(&'parent ArraySlice<'static, T>),
    MutSlice(&'parent MutArraySlice<'static, T>),
    Base(&'parent ArrayBase<T>),
}

/// An immutable slice of a multi-dimensional array
pub struct ArraySlice<'parent, T:'static> {
    parent: ArrayParent<'parent, T>,
    idx: usize,
}

impl<'parent, T> Array<T> for ArraySlice<'parent, T> {
    fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo] {
        let info = match self.parent {
            ArrayParent::Slice(p) => p.dimension_info(),
            ArrayParent::MutSlice(p) => p.dimension_info(),
            ArrayParent::Base(p) => p.dimension_info()
        };
        &info[1..]
    }

    fn slice<'a>(&'a self, idx: isize) -> ArraySlice<'a, T> {
        assert!(self.dimension_info().len() != 1,
                "Attempted to slice a one-dimensional array");
        unsafe {
            ArraySlice {
                parent: ArrayParent::Slice(mem::transmute(self)),
                idx: self.shift_idx(idx),
            }
        }
    }

    fn get<'a>(&'a self, idx: isize) -> &'a T {
        assert!(self.dimension_info().len() == 1,
                "Attempted to get from a multi-dimensional array");
        self.raw_get(self.shift_idx(idx), 1)
    }
}

impl<'parent, T> InternalArray<T> for ArraySlice<'parent, T> {
    fn raw_get<'a>(&'a self, idx: usize, size: usize) -> &'a T {
        let size = size * self.dimension_info()[0].len;
        let idx = size * self.idx + idx;
        match self.parent {
            ArrayParent::Slice(p) => p.raw_get(idx, size),
            ArrayParent::MutSlice(p) => p.raw_get(idx, size),
            ArrayParent::Base(p) => p.raw_get(idx, size)
        }
    }
}

enum MutArrayParent<'parent, T:'static> {
    Slice(&'parent mut MutArraySlice<'static, T>),
    Base(&'parent mut ArrayBase<T>),
}

/// A mutable slice of a multi-dimensional array
pub struct MutArraySlice<'parent, T:'static> {
    parent: MutArrayParent<'parent, T>,
    idx: usize,
}

impl<'parent, T> Array<T> for MutArraySlice<'parent, T> {
    fn dimension_info<'a>(&'a self) -> &'a [DimensionInfo] {
        let info : &'a [DimensionInfo] = unsafe {
            match self.parent {
                MutArrayParent::Slice(ref p) => mem::transmute(p.dimension_info()),
                MutArrayParent::Base(ref p) => mem::transmute(p.dimension_info()),
            }
        };
        &info[1..]
    }

    fn slice<'a>(&'a self, idx: isize) -> ArraySlice<'a, T> {
        assert!(self.dimension_info().len() != 1,
                "Attempted to slice a one-dimensional array");
        unsafe {
            ArraySlice {
                parent: ArrayParent::MutSlice(mem::transmute(self)),
                idx: self.shift_idx(idx),
            }
        }
    }

    fn get<'a>(&'a self, idx: isize) -> &'a T {
        assert!(self.dimension_info().len() == 1,
                "Attempted to get from a multi-dimensional array");
        self.raw_get(self.shift_idx(idx), 1)
    }
}

impl<'parent, T> MutableArray<T> for MutArraySlice<'parent, T> {
    fn slice_mut<'a>(&'a mut self, idx: isize) -> MutArraySlice<'a, T> {
        assert!(self.dimension_info().len() != 1,
                "Attempted to slice_mut a one-dimensional array");
        unsafe {
            MutArraySlice {
                idx: self.shift_idx(idx),
                parent: MutArrayParent::Slice(mem::transmute(self)),
            }
        }
    }

    fn get_mut<'a>(&'a mut self, idx: isize) -> &'a mut T {
        assert!(self.dimension_info().len() == 1,
                "Attempted to get_mut from a multi-dimensional array");
        let idx = self.shift_idx(idx);
        self.raw_get_mut(idx, 1)
    }
}

impl<'parent, T> InternalArray<T> for MutArraySlice<'parent, T> {
    fn raw_get<'a>(&'a self, idx: usize, size: usize) -> &'a T {
        let size = size * self.dimension_info()[0].len;
        let idx = size * self.idx + idx;
        unsafe {
            match self.parent {
                MutArrayParent::Slice(ref p) => mem::transmute(p.raw_get(idx, size)),
                MutArrayParent::Base(ref p) => mem::transmute(p.raw_get(idx, size))
            }
        }
    }
}

impl<'parent, T> InternalMutableArray<T> for MutArraySlice<'parent, T> {
    fn raw_get_mut<'a>(&'a mut self, idx: usize, size: usize) -> &'a mut T {
        let size = size * self.dimension_info()[0].len;
        let idx = size * self.idx + idx;
        unsafe {
            match self.parent {
                MutArrayParent::Slice(ref mut p) => mem::transmute(p.raw_get_mut(idx, size)),
                MutArrayParent::Base(ref mut p) => mem::transmute(p.raw_get_mut(idx, size))
            }
        }
    }
}

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

    #[test]
    fn test_from_vec() {
        let a = ArrayBase::from_vec(vec!(0i32, 1, 2), -1);
        assert!(&[DimensionInfo { len: 3, lower_bound: -1 }][..] ==
                a.dimension_info());
        assert_eq!(&0, a.get(-1));
        assert_eq!(&1, a.get(0));
        assert_eq!(&2, a.get(1));
    }

    #[test]
    #[should_panic]
    fn test_get_2d_fail() {
        let mut a = ArrayBase::from_vec(vec!(0i32, 1, 2), -1);
        a.wrap(1);
        a.get(1);
    }

    #[test]
    #[should_panic]
    fn test_2d_slice_range_fail_low() {
        let mut a = ArrayBase::from_vec(vec!(0i32, 1, 2), -1);
        a.wrap(1);
        a.slice(0);
    }

    #[test]
    #[should_panic]
    fn test_2d_slice_range_fail_high() {
        let mut a = ArrayBase::from_vec(vec!(0i32, 1, 2), -1);
        a.wrap(1);
        a.slice(2);
    }

    #[test]
    fn test_2d_slice_get() {
        let mut a = ArrayBase::from_vec(vec!(0i32, 1, 2), -1);
        a.wrap(1);
        let s = a.slice(1);
        assert_eq!(&0, s.get(-1));
        assert_eq!(&1, s.get(0));
        assert_eq!(&2, s.get(1));
    }

    #[test]
    #[should_panic]
    fn test_push_move_wrong_lower_bound() {
        let mut a = ArrayBase::from_vec(vec!(1i32), -1);
        a.push_move(ArrayBase::from_vec(vec!(2), 0));
    }

    #[test]
    #[should_panic]
    fn test_push_move_wrong_dims() {
        let mut a = ArrayBase::from_vec(vec!(1i32), -1);
        a.wrap(1);
        a.push_move(ArrayBase::from_vec(vec!(1, 2), -1));
    }

    #[test]
    #[should_panic]
    fn test_push_move_wrong_dim_count() {
        let mut a = ArrayBase::from_vec(vec!(1i32), -1);
        a.wrap(1);
        let mut b = ArrayBase::from_vec(vec!(2), -1);
        b.wrap(1);
        a.push_move(b);
    }

    #[test]
    fn test_push_move_ok() {
        let mut a = ArrayBase::from_vec(vec!(1i32, 2), 0);
        a.wrap(0);
        a.push_move(ArrayBase::from_vec(vec!(3, 4), 0));
        let s = a.slice(0);
        assert_eq!(&1, s.get(0));
        assert_eq!(&2, s.get(1));
        let s = a.slice(1);
        assert_eq!(&3, s.get(0));
        assert_eq!(&4, s.get(1));
    }

    #[test]
    fn test_3d() {
        let mut a = ArrayBase::from_vec(vec!(0i32, 1), 0);
        a.wrap(0);
        a.push_move(ArrayBase::from_vec(vec!(2, 3), 0));
        a.wrap(0);
        let mut b = ArrayBase::from_vec(vec!(4, 5), 0);
        b.wrap(0);
        b.push_move(ArrayBase::from_vec(vec!(6, 7), 0));
        a.push_move(b);
        let s1 = a.slice(0);
        let s2 = s1.slice(0);
        assert_eq!(&0, s2.get(0));
        assert_eq!(&1, s2.get(1));
        let s2 = s1.slice(1);
        assert_eq!(&2, s2.get(0));
        assert_eq!(&3, s2.get(1));
        let s1 = a.slice(1);
        let s2 = s1.slice(0);
        assert_eq!(&4, s2.get(0));
        assert_eq!(&5, s2.get(1));
        let s2 = s1.slice(1);
        assert_eq!(&6, s2.get(0));
        assert_eq!(&7, s2.get(1));
    }

    #[test]
    fn test_mut() {
        let mut a = ArrayBase::from_vec(vec!(1i32, 2), 0);
        a.wrap(0);
        {
            let mut s = a.slice_mut(0);
            *s.get_mut(0) = 3;
        }
        let s = a.slice(0);
        assert_eq!(&3, s.get(0));
    }

    #[test]
    #[should_panic]
    fn test_base_overslice() {
        let a = ArrayBase::from_vec(vec!(1i32), 0);
        a.slice(0);
    }

    #[test]
    #[should_panic]
    fn test_slice_overslice() {
        let mut a = ArrayBase::from_vec(vec!(1i32), 0);
        a.wrap(0);
        let s = a.slice(0);
        s.slice(0);
    }
}