1 // Copyright 2022 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use nom::{bytes, combinator};
16 
17 /// Nom parser for a `[u8; N]`.
parse_byte_array<const N: usize>(input: &[u8]) -> nom::IResult<&[u8], [u8; N]>18 pub(crate) fn parse_byte_array<const N: usize>(input: &[u8]) -> nom::IResult<&[u8], [u8; N]> {
19     combinator::map_res(bytes::complete::take(N), |slice: &[u8]| slice.try_into())(input)
20 }
21 
22 #[allow(clippy::unwrap_used)]
23 #[cfg(test)]
24 mod tests {
25     use super::*;
26 
27     #[test]
parse_empty_array()28     fn parse_empty_array() {
29         assert_eq!(([1_u8, 2, 3].as_slice(), []), parse_byte_array::<0>(&[1, 2, 3]).unwrap())
30     }
31 
32     #[test]
parse_nonempty_array()33     fn parse_nonempty_array() {
34         assert_eq!(
35             ([4_u8, 5, 6].as_slice(), [1, 2, 3]),
36             parse_byte_array::<3>(&[1, 2, 3, 4, 5, 6]).unwrap()
37         )
38     }
39 }
40