cv_bridge/utils/image_byteorder_ops.rs
1//! This module contains functions to convert between big and little endian byte order.
2use std::io::Cursor;
3use byteorder::{
4 LittleEndian,
5 BigEndian,
6 ReadBytesExt,
7 WriteBytesExt
8};
9
10/// Takes a u8 array and constructs a u16 array by converting
11/// two u8 values into one u16 value.
12///
13/// ## Arguments
14/// * `data` - The u8 array to convert.
15/// * `big_endian` - If true, the u8 array is in big endian byte order.
16/// If false, the u8 array is in little endian byte order.
17///
18/// ## Returns
19/// A u16 array.
20pub fn from_u8_to_u16(data: &[u8], big_endian: bool) -> Vec<u16> {
21 let mut data16 = Vec::with_capacity(data.len());
22 let mut cursor = Cursor::new(data);
23
24 if big_endian {
25 while let Ok(value) = cursor.read_u16::<BigEndian>() {
26 data16.push(value);
27 }
28 } else {
29 while let Ok(value) = cursor.read_u16::<LittleEndian>() {
30 data16.push(value);
31 }
32 }
33
34 data16
35}
36
37/// Takes a u16 array and constructs a u8 array by converting
38/// one u16 value into two u8 values.
39///
40/// ## Arguments
41/// * `data` - The u16 array to convert.
42/// * `big_endian` - If true, the u8 array will be in big endian byte order.
43/// If false, the u8 array will be in little endian byte order.
44///
45/// ## Returns
46/// A u8 array.
47pub fn from_u16_to_u8(data: &[u16], big_endian: bool) -> Vec<u8> {
48 let mut data8 = Vec::with_capacity(data.len());
49
50 if big_endian {
51 for value in data {
52 data8.write_u16::<BigEndian>(*value).unwrap();
53 }
54 } else {
55 for value in data {
56 data8.write_u16::<LittleEndian>(*value).unwrap();
57 }
58 }
59
60 data8
61}
62
63/// Takes a u8 array in big endian byte order and converts it to little endian byte order.
64///
65/// ## Arguments
66/// * `be` - The u8 array to convert.
67///
68/// ## Returns
69/// A u8 array in little endian byte order.
70pub fn from_be_to_le(be: &[u8]) -> Vec<u8> {
71 let mut le = Vec::with_capacity(be.len());
72 let mut cursor = Cursor::new(be);
73
74 while let Ok(value) = cursor.read_u16::<BigEndian>() {
75 le.write_u16::<LittleEndian>(value).unwrap();
76 }
77
78 le
79}
80
81/// Takes a u8 array in little endian byte order and converts it to big endian byte order.
82///
83/// ## Arguments
84/// * `le` - The u8 array to convert.
85///
86/// ## Returns
87/// A u8 array in big endian byte order.
88pub fn from_le_to_be(le: &[u8]) -> Vec<u8> {
89 let mut be = Vec::with_capacity(le.len());
90 let mut cursor = Cursor::new(le);
91
92 while let Ok(value) = cursor.read_u16::<LittleEndian>() {
93 be.write_u16::<BigEndian>(value).unwrap();
94 }
95
96 be
97}