msg_tool\utils/
str.rs

1//! String Utilities
2use crate::types::*;
3use crate::utils::encoding::*;
4use anyhow::Result;
5use unicode_segmentation::UnicodeSegmentation;
6
7/// Truncate a string to a specified length, encoding it with the given encoding.
8/// Output size may less than or equal to the specified length.
9pub fn truncate_string(s: &str, length: usize, encoding: Encoding, check: bool) -> Result<Vec<u8>> {
10    let vec: Vec<_> = UnicodeSegmentation::graphemes(s, true).collect();
11    let mut result = Vec::new();
12    for graphemes in vec {
13        let data = encode_string(encoding, graphemes, check)?;
14        if result.len() + data.len() > length {
15            break;
16        }
17        result.extend(data);
18    }
19    return Ok(result);
20}