binpool/
read_write.rs

1use std::io;
2
3use Bytes;
4use State;
5use Type;
6
7/// Implemented by array types.
8pub trait Array {
9    /// The type of item.
10    type Item;
11
12    /// Returns the number of items.
13    fn len(&self) -> usize;
14    /// Get value of item by index.
15    fn get(&self, ind: usize) -> &Self::Item;
16    /// Set value of item at index.
17    fn set(&mut self, ind: usize, val: Self::Item);
18    /// Push new item at the end of array.
19    fn push(&mut self, val: Self::Item);
20}
21
22impl<T> Array for Vec<T> {
23    type Item = T;
24
25    fn len(&self) -> usize {self.len()}
26    fn get(&self, ind: usize) -> &T {&self[ind]}
27    fn set(&mut self, ind: usize, val: T) {self[ind] = val}
28    fn push(&mut self, val: T) {
29        Vec::push(self, val)
30    }
31}
32
33/// Implemented by matrix types.
34pub trait Matrix: Sized + Default {
35    /// Scalar type.
36    type Scalar: Scalar;
37
38    /// Returns dimensions.
39    fn dim() -> [usize; 2];
40    /// Gets value.
41    fn get(&self, row: usize, col: usize) -> &Self::Scalar;
42    /// Sets value.
43    fn set(&mut self, row: usize, col: usize, val: Self::Scalar);
44
45    /// Writes property.
46    fn write_property<W: io::Write>(&self, property_id: u16, w: &mut W) -> io::Result<()> {
47        let dim = <Self as Matrix>::dim();
48        let (ty, s) = <Self::Scalar as Scalar>::ty().matrix(dim[0] as u8, dim[1] as u8).unwrap();
49        let state = State::new()
50            .write_type_format(ty, w)?
51            .write_property_id(property_id, w)?
52            .write_bytes(s, w)?
53            .write_offset_instance_id(0, w)?;
54        for i in 0..dim[0] {
55            for j in 0..dim[1] {
56                self.get(i, j).write(w)?;
57            }
58        }
59        state.end_data().end_bytes(w)?;
60        Ok(())
61    }
62
63    /// Writes array.
64    fn write_array<W: io::Write, A: Array<Item = Self>>(
65        property_id: u16,
66        arr: &A,
67        w: &mut W
68    ) -> io::Result<()> {
69        let dim = <Self as Matrix>::dim();
70        let n = arr.len();
71        let (ty, s) = <Self::Scalar as Scalar>::ty().matrix(dim[0] as u8, dim[1] as u8).unwrap();
72        let state = State::new()
73            .write_type_format(ty, w)?
74            .write_property_id(property_id, w)?
75            .write_bytes(s * n as u64, w)?
76            .write_offset_instance_id(0, w)?;
77        for k in 0..n {
78            let mat = arr.get(k);
79            for i in 0..dim[0] {
80                for j in 0..dim[1] {
81                    mat.get(i, j).write(w)?;
82                }
83            }
84        }
85        state.end_data().end_bytes(w)?;
86        Ok(())
87    }
88
89    /// Reads property.
90    fn read_property<R: io::Read>(
91        &mut self,
92        state: State<Bytes>,
93        ty: u16,
94        r: &mut R
95    ) -> io::Result<()> {
96        let dim = Self::dim();
97        let self_ty = Self::Scalar::ty();
98        if let Some((ty, rows, cols)) = Type::info(ty) {
99            if ty == self_ty && rows == dim[0] as u8 && cols == dim[1] as u8 {
100                let mut bytes = 0;
101                let state = state.read_bytes(&mut bytes, r)?;
102                let (_, scalar_bytes) = self_ty.matrix(dim[0] as u8, dim[1] as u8).unwrap();
103                if bytes == scalar_bytes {
104                    let mut offset = 0;
105                    let state = state.read_offset_instance_id(&mut offset, r)?;
106                    if offset == 0 {
107                        for i in 0..dim[0] {
108                            for j in 0..dim[1] {
109                                let mut scalar: Self::Scalar = Default::default();
110                                scalar.read(r)?;
111                                self.set(i, j, scalar);
112                            }
113                        }
114                        state.end_data().has_end_bytes(r)?;
115                        return Ok(())
116                    }
117                }
118            }
119        }
120        return Err(io::ErrorKind::InvalidData.into())
121    }
122
123    /// Reads array.
124    fn read_array<R: io::Read, A: Array<Item = Self>>(
125        state: State<Bytes>,
126        ty: u16,
127        arr: &mut A,
128        r: &mut R
129    ) -> io::Result<()> {
130        use std::usize;
131
132        let dim = <Self as Matrix>::dim();
133        let self_ty = <Self::Scalar as Scalar>::ty();
134        if let Some((ty, rows, cols)) = Type::info(ty) {
135            if ty == self_ty && rows == dim[0] as u8 && cols == dim[1] as u8 {
136                let mut bytes = 0;
137                let state = state.read_bytes(&mut bytes, r)?;
138                let (_, scalar_bytes) = self_ty.matrix(dim[0] as u8, dim[1] as u8).unwrap();
139                if bytes % scalar_bytes == 0 {
140                    let n = bytes / scalar_bytes;
141                    let mut offset = 0;
142                    let state = state.read_offset_instance_id(&mut offset, r)?;
143                    for i in offset..(offset + n) {
144                        if i > usize::MAX as u64 {
145                            return Err(io::ErrorKind::Other.into());
146                        }
147                        while i as usize >= arr.len() {
148                            arr.push(Default::default());
149                        }
150                        let mut vector: Self = Default::default();
151                        for i in 0..dim[0] {
152                            for j in 0..dim[1] {
153                                let mut scalar: Self::Scalar = Default::default();
154                                scalar.read(r)?;
155                                vector.set(i, j, scalar);
156                            }
157                        }
158                        arr.set(i as usize, vector);
159                    }
160                    state.end_data().has_end_bytes(r)?;
161                    return Ok(())
162                }
163            }
164        }
165        return Err(io::ErrorKind::InvalidData.into())
166    }
167}
168
169impl<T: Scalar> Matrix for [[T; 2]; 2] {
170    type Scalar = T;
171
172    #[inline]
173    fn dim() -> [usize; 2] {[2, 2]}
174    #[inline]
175    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
176    #[inline]
177    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
178}
179
180impl<T: Scalar> Matrix for [[T; 2]; 3] {
181    type Scalar = T;
182
183    #[inline]
184    fn dim() -> [usize; 2] {[3, 2]}
185    #[inline]
186    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
187    #[inline]
188    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
189}
190
191impl<T: Scalar> Matrix for [[T; 2]; 4] {
192    type Scalar = T;
193
194    #[inline]
195    fn dim() -> [usize; 2] {[4, 2]}
196    #[inline]
197    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
198    #[inline]
199    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
200}
201
202impl<T: Scalar> Matrix for [[T; 3]; 2] {
203    type Scalar = T;
204
205    #[inline]
206    fn dim() -> [usize; 2] {[2, 3]}
207    #[inline]
208    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
209    #[inline]
210    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
211}
212
213
214impl<T: Scalar> Matrix for [[T; 3]; 3] {
215    type Scalar = T;
216
217    #[inline]
218    fn dim() -> [usize; 2] {[3, 3]}
219    #[inline]
220    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
221    #[inline]
222    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
223}
224
225impl<T: Scalar> Matrix for [[T; 3]; 4] {
226    type Scalar = T;
227
228    #[inline]
229    fn dim() -> [usize; 2] {[4, 3]}
230    #[inline]
231    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
232    #[inline]
233    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
234}
235
236impl<T: Scalar> Matrix for [[T; 4]; 2] {
237    type Scalar = T;
238
239    #[inline]
240    fn dim() -> [usize; 2] {[2, 4]}
241    #[inline]
242    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
243    #[inline]
244    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
245}
246
247impl<T: Scalar> Matrix for [[T; 4]; 3] {
248    type Scalar = T;
249
250    #[inline]
251    fn dim() -> [usize; 2] {[3, 4]}
252    #[inline]
253    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
254    #[inline]
255    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
256}
257
258impl<T: Scalar> Matrix for [[T; 4]; 4] {
259    type Scalar = T;
260
261    #[inline]
262    fn dim() -> [usize; 2] {[4, 4]}
263    #[inline]
264    fn get(&self, row: usize, col: usize) -> &T {&self[row][col]}
265    #[inline]
266    fn set(&mut self, row: usize, col: usize, val: T) {self[row][col] = val}
267}
268
269/// Implemented by vector types.
270pub trait Vector: Sized + Default {
271    /// Scalar type.
272    type Scalar: Scalar;
273
274    /// Returns the number of dimensions.
275    fn dim() -> usize;
276    /// Gets value.
277    fn get(&self, ind: usize) -> &Self::Scalar;
278    /// Sets value.
279    fn set(&mut self, ind: usize, val: Self::Scalar);
280
281    /// Writes property.
282    fn write_property<W: io::Write>(&self, property_id: u16, w: &mut W) -> io::Result<()> {
283        let dim = <Self as Vector>::dim();
284        let (ty, s) = <Self::Scalar as Scalar>::ty().vector(dim as u8).unwrap();
285        let state = State::new()
286            .write_type_format(ty, w)?
287            .write_property_id(property_id, w)?
288            .write_bytes(s, w)?
289            .write_offset_instance_id(0, w)?;
290        for i in 0..dim {
291            self.get(i).write(w)?;
292        }
293        state.end_data().end_bytes(w)?;
294        Ok(())
295    }
296
297    /// Writes array.
298    fn write_array<W: io::Write, A: Array<Item = Self>>(
299        property_id: u16,
300        arr: &A,
301        w: &mut W
302    ) -> io::Result<()> {
303        let dim = <Self as Vector>::dim();
304        let n = arr.len();
305        let (ty, s) = <Self::Scalar as Scalar>::ty().vector(dim as u8).unwrap();
306        let state = State::new()
307            .write_type_format(ty, w)?
308            .write_property_id(property_id, w)?
309            .write_bytes(s * n as u64, w)?
310            .write_offset_instance_id(0, w)?;
311        for k in 0..n {
312            let v = arr.get(k);
313            for i in 0..dim {
314                v.get(i).write(w)?;
315            }
316        }
317        state.end_data().end_bytes(w)?;
318        Ok(())
319    }
320
321    /// Reads property.
322    fn read_property<R: io::Read>(
323        &mut self,
324        state: State<Bytes>,
325        ty: u16,
326        r: &mut R
327    ) -> io::Result<()> {
328        let dim = Self::dim();
329        let self_ty = Self::Scalar::ty();
330        if let Some((ty, rows, cols)) = Type::info(ty) {
331            if ty == self_ty && rows == 1 && cols == dim as u8 {
332                let mut bytes = 0;
333                let state = state.read_bytes(&mut bytes, r)?;
334                let (_, scalar_bytes) = self_ty.vector(dim as u8).unwrap();
335                if bytes == scalar_bytes {
336                    let mut offset = 0;
337                    let state = state.read_offset_instance_id(&mut offset, r)?;
338                    if offset == 0 {
339                        for i in 0..dim {
340                            let mut scalar: Self::Scalar = Default::default();
341                            scalar.read(r)?;
342                            self.set(i, scalar);
343                        }
344                        state.end_data().has_end_bytes(r)?;
345                        return Ok(())
346                    }
347                }
348            }
349        }
350        return Err(io::ErrorKind::InvalidData.into())
351    }
352
353    /// Reads array.
354    fn read_array<R: io::Read, A: Array<Item = Self>>(
355        state: State<Bytes>,
356        ty: u16,
357        arr: &mut A,
358        r: &mut R
359    ) -> io::Result<()> {
360        use std::usize;
361
362        let dim = <Self as Vector>::dim();
363        let self_ty = <Self::Scalar as Scalar>::ty();
364        if let Some((ty, rows, cols)) = Type::info(ty) {
365            if ty == self_ty && rows == 1 && cols == dim as u8 {
366                let mut bytes = 0;
367                let state = state.read_bytes(&mut bytes, r)?;
368                let (_, scalar_bytes) = self_ty.vector(dim as u8).unwrap();
369                if bytes % scalar_bytes == 0 {
370                    let n = bytes / scalar_bytes;
371                    let mut offset = 0;
372                    let state = state.read_offset_instance_id(&mut offset, r)?;
373                    for i in offset..(offset + n) {
374                        if i > usize::MAX as u64 {
375                            return Err(io::ErrorKind::Other.into());
376                        }
377                        while i as usize >= arr.len() {
378                            arr.push(Default::default());
379                        }
380                        let mut vector: Self = Default::default();
381                        for i in 0..dim {
382                            let mut scalar: Self::Scalar = Default::default();
383                            scalar.read(r)?;
384                            vector.set(i, scalar);
385                        }
386                        arr.set(i as usize, vector);
387                    }
388                    state.end_data().has_end_bytes(r)?;
389                    return Ok(())
390                }
391            }
392        }
393        return Err(io::ErrorKind::InvalidData.into())
394    }
395}
396
397impl<T: Scalar> Vector for [T; 2] {
398    type Scalar = T;
399
400    #[inline]
401    fn dim() -> usize {2}
402    #[inline]
403    fn get(&self, ind: usize) -> &T {&self[ind]}
404    #[inline]
405    fn set(&mut self, ind: usize, val: T) {self[ind] = val}
406}
407
408impl<T: Scalar> Vector for [T; 3] {
409    type Scalar = T;
410
411    #[inline]
412    fn dim() -> usize {3}
413    #[inline]
414    fn get(&self, ind: usize) -> &T {&self[ind]}
415    #[inline]
416    fn set(&mut self, ind: usize, val: T) {self[ind] = val}
417}
418
419impl<T: Scalar> Vector for [T; 4] {
420    type Scalar = T;
421
422    #[inline]
423    fn dim() -> usize {4}
424    #[inline]
425    fn get(&self, ind: usize) -> &T {&self[ind]}
426    #[inline]
427    fn set(&mut self, ind: usize, val: T) {self[ind] = val}
428}
429
430/// Implemented by scalar values.
431pub trait Scalar: Sized + Default {
432    /// Type of scalar.
433    fn ty() -> Type;
434    /// Write to binary.
435    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize>;
436    /// Read from binary.
437    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize>;
438
439    /// Writes property.
440    fn write_property<W: io::Write>(&self, property_id: u16, w: &mut W) -> io::Result<()> {
441        let (ty, s) = <Self as Scalar>::ty().scalar();
442        let state = State::new()
443            .write_type_format(ty, w)?
444            .write_property_id(property_id, w)?
445            .write_bytes(s, w)?
446            .write_offset_instance_id(0, w)?;
447        self.write(w)?;
448        state.end_data().end_bytes(w)?;
449        Ok(())
450    }
451
452    /// Writes array.
453    fn write_array<W: io::Write, A: Array<Item = Self>>(
454        property_id: u16,
455        arr: &A,
456        w: &mut W
457    ) -> io::Result<()> {
458        let n = arr.len();
459        let (ty, s) = <Self as Scalar>::ty().scalar();
460        let state = State::new()
461            .write_type_format(ty, w)?
462            .write_property_id(property_id, w)?
463            .write_bytes(s * n as u64, w)?
464            .write_offset_instance_id(0, w)?;
465        for k in 0..n {
466            let s = arr.get(k);
467            s.write(w)?;
468        }
469        state.end_data().end_bytes(w)?;
470        Ok(())
471    }
472
473    /// Reads property.
474    fn read_property<R: io::Read>(&mut self, state: State<Bytes>, ty: u16, r: &mut R) -> io::Result<()> {
475        let self_ty = <Self as Scalar>::ty();
476        if let Some((ty, rows, cols)) = Type::info(ty) {
477            if ty == self_ty && rows == 1 && cols == 1 {
478                let mut bytes = 0;
479                let state = state.read_bytes(&mut bytes, r)?;
480                let (_, scalar_bytes) = self_ty.scalar();
481                if bytes == scalar_bytes {
482                    let mut offset = 0;
483                    let state = state.read_offset_instance_id(&mut offset, r)?;
484                    if offset == 0 {
485                        self.read(r)?;
486                        state.end_data().has_end_bytes(r)?;
487                        return Ok(())
488                    }
489                }
490            }
491        }
492        return Err(io::ErrorKind::InvalidData.into())
493    }
494
495    /// Reads array.
496    fn read_array<R: io::Read, A: Array<Item = Self>>(
497        state: State<Bytes>,
498        ty: u16,
499        arr: &mut A,
500        r: &mut R
501    ) -> io::Result<()> {
502        use std::usize;
503
504        let self_ty = <Self as Scalar>::ty();
505        if let Some((ty, rows, cols)) = Type::info(ty) {
506            if ty == self_ty && rows == 1 && cols == 1 {
507                let mut bytes = 0;
508                let state = state.read_bytes(&mut bytes, r)?;
509                let (_, scalar_bytes) = self_ty.scalar();
510                if bytes % scalar_bytes == 0 {
511                    let n = bytes / scalar_bytes;
512                    let mut offset = 0;
513                    let state = state.read_offset_instance_id(&mut offset, r)?;
514                    for i in offset..(offset + n) {
515                        if i > usize::MAX as u64 {
516                            return Err(io::ErrorKind::Other.into());
517                        }
518                        while i as usize >= arr.len() {
519                            arr.push(Default::default());
520                        }
521                        let mut scalar: Self = Default::default();
522                        scalar.read(r)?;
523                        arr.set(i as usize, scalar);
524                    }
525                    state.end_data().has_end_bytes(r)?;
526                    return Ok(())
527                }
528            }
529        }
530        return Err(io::ErrorKind::InvalidData.into())
531    }
532}
533
534impl Scalar for u8 {
535    #[inline]
536    fn ty() -> Type {Type::U8}
537    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
538        w.write(&[*self])
539    }
540    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
541        let mut buf: [u8; 1] = [0; 1];
542        r.read_exact(&mut buf)?;
543        *self = buf[0];
544        Ok(1)
545    }
546}
547
548impl Scalar for u16 {
549    #[inline]
550    fn ty() -> Type {Type::U16}
551    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
552        let le = self.to_le();
553        w.write(&[le as u8, (le >> 8) as u8])
554    }
555    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
556        let mut buf: [u8; 2] = [0; 2];
557        r.read_exact(&mut buf)?;
558        *self = u16::from_le(buf[0] as u16 | (buf[1] as u16) << 8);
559        Ok(2)
560    }
561}
562
563impl Scalar for u32 {
564    #[inline]
565    fn ty() -> Type {Type::U32}
566    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
567        let le = self.to_le();
568        w.write(&[le as u8, (le >> 8) as u8, (le >> 16) as u8, (le >> 24) as u8])
569    }
570    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
571        let mut buf: [u8; 4] = [0; 4];
572        r.read_exact(&mut buf)?;
573        *self = u32::from_le(
574            buf[0] as u32 | (buf[1] as u32) << 8 |
575            (buf[2] as u32) << 16 | (buf[3] as u32) << 24
576        );
577        Ok(4)
578    }
579}
580
581impl Scalar for u64 {
582    #[inline]
583    fn ty() -> Type {Type::U64}
584    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
585        let le = self.to_le();
586        w.write(&[
587            le as u8, (le >> 8) as u8, (le >> 16) as u8, (le >> 24) as u8,
588            (le >> 32) as u8, (le >> 40) as u8, (le >> 48) as u8, (le >> 56) as u8
589        ])
590    }
591    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
592        let mut buf: [u8; 8] = [0; 8];
593        r.read_exact(&mut buf)?;
594        *self = u64::from_le(
595            buf[0] as u64 | (buf[1] as u64) << 8 |
596            (buf[2] as u64) << 16 | (buf[3] as u64) << 24 |
597            (buf[4] as u64) << 32 | (buf[5] as u64) << 40 |
598            (buf[6] as u64) << 48 | (buf[7] as u64) << 56
599        );
600        Ok(8)
601    }
602}
603
604impl Scalar for i8 {
605    #[inline]
606    fn ty() -> Type {Type::I8}
607    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
608        w.write(&[*self as u8])
609    }
610    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
611        let mut val: u8 = 0;
612        let n = val.read(r)?;
613        *self = val as i8;
614        Ok(n)
615    }
616}
617
618impl Scalar for i16 {
619    #[inline]
620    fn ty() -> Type {Type::I8}
621    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
622        (*self as u16).write(w)
623    }
624    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
625        let mut val: u16 = 0;
626        let n = val.read(r)?;
627        *self = val as i16;
628        Ok(n)
629    }
630}
631
632impl Scalar for i32 {
633    #[inline]
634    fn ty() -> Type {Type::I8}
635    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
636        (*self as u32).write(w)
637    }
638    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
639        let mut val: u32 = 0;
640        let n = val.read(r)?;
641        *self = val as i32;
642        Ok(n)
643    }
644}
645
646impl Scalar for i64 {
647    #[inline]
648    fn ty() -> Type {Type::I8}
649    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
650        (*self as u64).write(w)
651    }
652    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
653        let mut val: u64 = 0;
654        let n = val.read(r)?;
655        *self = val as i64;
656        Ok(n)
657    }
658}
659
660impl Scalar for f32 {
661    #[inline]
662    fn ty() -> Type {Type::I8}
663    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
664        use std::mem::transmute;
665
666        unsafe {transmute::<&f32, &u32>(self)}.write(w)
667    }
668    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
669        use std::mem::transmute;
670
671        let mut val: u32 = 0;
672        let n = val.read(r)?;
673        *self = unsafe {transmute::<u32, f32>(val)};
674        Ok(n)
675    }
676}
677
678impl Scalar for f64 {
679    #[inline]
680    fn ty() -> Type {Type::I8}
681    fn write<W: io::Write>(&self, w: &mut W) -> io::Result<usize> {
682        use std::mem::transmute;
683
684        unsafe {transmute::<&f64, &u64>(self)}.write(w)
685    }
686    fn read<R: io::Read>(&mut self, r: &mut R) -> io::Result<usize> {
687        use std::mem::transmute;
688
689        let mut val: u64 = 0;
690        let n = val.read(r)?;
691        *self = unsafe {transmute::<u64, f64>(val)};
692        Ok(n)
693    }
694}