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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use bytes::Bytes;
use libc;
use std::mem;
use std::slice;

use super::datatypes::*;
use super::memory::*;

/// Buffer<T> is essentially just a Vec<T> for fixed-width primitive types and the start of the
/// memory region is aligned at a 64-byte boundary
pub struct Buffer<T>
where
    T: ArrowPrimitiveType,
{
    /// Contiguous memory region holding instances of primitive T
    data: *const T,
    /// Number of elements in the buffer
    len: usize,
}

impl<T> Buffer<T>
where
    T: ArrowPrimitiveType,
{
    /// create a buffer from an existing region of memory (must already be byte-aligned)
    pub unsafe fn from_raw_parts(data: *const T, len: usize) -> Self {
        Buffer { data, len }
    }

    /// Get the number of elements in the buffer
    pub fn len(&self) -> usize {
        self.len
    }

    /// Get a pointer to the data contained by the buffer
    pub fn data(&self) -> *const T {
        self.data
    }

    pub fn slice(&self, start: usize, end: usize) -> &[T] {
        assert!(end <= self.len);
        assert!(start <= end);
        unsafe { slice::from_raw_parts(self.data.offset(start as isize), end - start) }
    }

    /// Get a reference to the value at the specified offset
    pub fn get(&self, i: usize) -> &T {
        assert!(i < self.len);
        unsafe { &(*self.data.offset(i as isize)) }
    }

    /// Write to a slot in the buffer
    pub fn set(&mut self, i: usize, v: T) {
        assert!(i < self.len);
        let p = self.data as *mut T;
        unsafe {
            *p.offset(i as isize) = v;
        }
    }

    /// Return an iterator over the values in the buffer
    pub fn iter(&self) -> BufferIterator<T> {
        BufferIterator {
            data: self.data,
            len: self.len,
            index: 0,
        }
    }
}

/// Release the underlying memory when the Buffer goes out of scope
impl<T> Drop for Buffer<T>
where
    T: ArrowPrimitiveType,
{
    fn drop(&mut self) {
        if !self.data.is_null() {
            free_aligned(self.data as *const u8);
            self.data = std::ptr::null_mut();
        }
    }
}

/// Iterator over the elements of a buffer
pub struct BufferIterator<T>
where
    T: ArrowPrimitiveType,
{
    data: *const T,
    len: usize,
    index: isize,
}

impl<T> Iterator for BufferIterator<T>
where
    T: ArrowPrimitiveType,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.len as isize {
            let value = unsafe { *self.data.offset(self.index) };
            self.index += 1;
            Some(value)
        } else {
            None
        }
    }
}

/// Copy the memory from a Vec<T> into a newly allocated Buffer<T>
impl<T> From<Vec<T>> for Buffer<T>
where
    T: ArrowPrimitiveType,
{
    fn from(v: Vec<T>) -> Self {
        // allocate aligned memory buffer
        let len = v.len();
        let sz = mem::size_of::<T>();
        let buffer = allocate_aligned((len * sz) as i64).unwrap();
        Buffer {
            len,
            data: unsafe {
                let dst = mem::transmute::<*const u8, *mut libc::c_void>(buffer);
                libc::memcpy(
                    dst,
                    mem::transmute::<*const T, *const libc::c_void>(v.as_ptr()),
                    len * sz,
                );
                mem::transmute::<*mut libc::c_void, *const T>(dst)
            },
        }
    }
}

impl From<Bytes> for Buffer<u8> {
    fn from(bytes: Bytes) -> Self {
        // allocate aligned
        let len = bytes.len();
        let sz = mem::size_of::<u8>();
        let buf_mem = allocate_aligned((len * sz) as i64).unwrap();
        let dst = buf_mem as *mut libc::c_void;
        Buffer {
            len,
            data: unsafe {
                libc::memcpy(dst, bytes.as_ptr() as *const libc::c_void, len * sz);
                dst as *mut u8
            },
        }
    }
}

unsafe impl<T: ArrowPrimitiveType> Sync for Buffer<T> {}
unsafe impl<T: ArrowPrimitiveType> Send for Buffer<T> {}

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

    #[test]
    fn test_buffer_i32() {
        let b: Buffer<i32> = Buffer::from(vec![1, 2, 3, 4, 5]);
        assert_eq!(5, b.len);
    }

    #[test]
    fn test_iterator_i32() {
        let b: Buffer<i32> = Buffer::from(vec![1, 2, 3, 4, 5]);
        let it = b.iter();
        let v: Vec<i32> = it.map(|n| n + 1).collect();
        assert_eq!(vec![2, 3, 4, 5, 6], v);
    }

    #[test]
    fn test_buffer_eq() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let b = Buffer::from(vec![5, 4, 3, 2, 1]);
        let c = a.iter()
            .zip(b.iter())
            .map(|(a, b)| a == b)
            .collect::<Vec<bool>>();
        assert_eq!(c, vec![false, false, true, false, false]);
    }

    #[test]
    fn test_buffer_lt() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let b = Buffer::from(vec![5, 4, 3, 2, 1]);
        let c = a.iter()
            .zip(b.iter())
            .map(|(a, b)| a < b)
            .collect::<Vec<bool>>();
        assert_eq!(c, vec![true, true, false, false, false]);
    }

    #[test]
    fn test_buffer_gt() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let b = Buffer::from(vec![5, 4, 3, 2, 1]);
        let c = a.iter()
            .zip(b.iter())
            .map(|(a, b)| a > b)
            .collect::<Vec<bool>>();
        assert_eq!(c, vec![false, false, false, true, true]);
    }

    #[test]
    fn test_buffer_add() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let b = Buffer::from(vec![5, 4, 3, 2, 1]);
        let c = a.iter()
            .zip(b.iter())
            .map(|(a, b)| a + b)
            .collect::<Vec<i32>>();
        assert_eq!(c, vec![6, 6, 6, 6, 6]);
    }

    #[test]
    fn test_buffer_multiply() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let b = Buffer::from(vec![5, 4, 3, 2, 1]);
        let c = a.iter()
            .zip(b.iter())
            .map(|(a, b)| a * b)
            .collect::<Vec<i32>>();
        assert_eq!(c, vec![5, 8, 9, 8, 5]);
    }

    #[test]
    #[should_panic]
    fn test_get_out_of_bounds() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        a.get(123); // should panic
    }

    #[test]
    fn slice_empty_at_end() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        let s = a.slice(5, 5);
        assert_eq!(0, s.len());
    }

    #[test]
    #[should_panic]
    fn slice_start_out_of_bounds() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        a.slice(6, 6); // should panic
    }

    #[test]
    #[should_panic]
    fn slice_end_out_of_bounds() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        a.slice(0, 6); // should panic
    }

    #[test]
    #[should_panic]
    fn slice_end_before_start() {
        let a = Buffer::from(vec![1, 2, 3, 4, 5]);
        a.slice(3, 2); // should panic
    }

    #[test]
    fn test_access_buffer_concurrently() {
        let buffer = Buffer::from(vec![1, 2, 3, 4, 5]);
        assert_eq!(vec![1, 2, 3, 4, 5], buffer.iter().collect::<Vec<i32>>());

        let collected_vec = thread::spawn(move || {
            // access buffer in another thread.
            buffer.iter().collect::<Vec<i32>>()
        }).join();

        assert!(collected_vec.is_ok());
        assert_eq!(vec![1, 2, 3, 4, 5], collected_vec.ok().unwrap());
    }
}