fuga_remo_api/
parser_options.rs

1// Parser options
2// Copyright 2022-2023 Kenta Ida 
3// SPDX-License-Identifier: MIT
4//
5
6use core::str::FromStr;
7
8use heapless::String;
9use crate::common_types::ModelNodeParseError;
10
11pub struct ParserOptions {
12    /// Truncate strings if the length is too long to hold.
13    truncate_too_long_string: bool,
14}
15
16impl Default for ParserOptions {
17    fn default() -> Self {
18        Self {
19            truncate_too_long_string: true,
20        }
21    }
22}
23
24/// Copy string as long as the storage can hold.
25pub fn copy_string_possible<const N: usize>(s: &str) -> String<N> {
26    let mut string = String::new();
27    for c in s.chars() {
28        if let Err(_) = string.push(c) {
29            break;
30        }
31    }
32    string
33}
34
35/// Copy string. Truncate extra characters which cannot be held by the storage if options.truncate_too_long_string is true.
36pub fn copy_string_option<const N: usize>(s: &str, options: &ParserOptions) -> Result<String<N>, ModelNodeParseError> {
37    if options.truncate_too_long_string {
38        Ok(copy_string_possible(s))
39    } else {
40        String::from_str(s).map_err(|_| ModelNodeParseError::StringTooLong)
41    }
42}