| 1 | #[derive(PartialEq)] |
| 2 | pub enum BOM { |
| 3 | BigEndian, |
| 4 | LittleEndian, |
| 5 | None, |
| 6 | } |
| 7 | |
| 8 | pub fn convert_to_u16(str: &str, bom: BOM) -> Vec<u8> { |
| 9 | let mut bytes = vec![]; |
| 10 | |
| 11 | if bom == BOM::BigEndian { |
| 12 | bytes = core::iter::once(0xFEFF) |
| 13 | .chain(str.encode_utf16()) |
| 14 | .flat_map(|word| word.to_be_bytes()) |
| 15 | .collect::<Vec<_>>(); |
| 16 | } else if bom == BOM::LittleEndian { |
| 17 | bytes = core::iter::once(0xFFFE) |
| 18 | .chain(str.encode_utf16()) |
| 19 | .flat_map(|word| word.to_le_bytes()) |
| 20 | .collect::<Vec<_>>(); |
| 21 | } else if bom == BOM::None { |
| 22 | let utf16 = str.encode_utf16(); |
| 23 | |
| 24 | // autodetect endianess |
| 25 | if cfg!(target_endian = "big") { |
| 26 | bytes = utf16 |
| 27 | .flat_map(|word| word.to_be_bytes()) |
| 28 | .collect::<Vec<_>>(); |
| 29 | } else { |
| 30 | bytes = utf16 |
| 31 | .flat_map(|word| word.to_le_bytes()) |
| 32 | .collect::<Vec<_>>(); |
| 33 | } |
| 34 | } |
| 35 | bytes |
| 36 | } |