Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / third_party / betocore / np_adv / src / helpers.rs

helpers.rs39 lines · 1.2 KiBRaw
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
15use nom::{bytes, combinator, Parser as _};
16
17/// Nom parser for a `[u8; N]`.
18pub(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()).parse(input)
20}
21
22#[allow(clippy::unwrap_used)]
23#[cfg(test)]
24mod tests {
25 use super::*;
26
27 #[test]
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]
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}