shell_rs/core/str.rs
1// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5use crate::error::Error;
6
7/// Convert C string slice to string slice
8/// C string slice may be postfixed with multiple null characters.
9pub fn cstr_to_str(input: &[u8]) -> Result<&str, Error> {
10 let nul_index = input.iter().position(|&b| b == 0).unwrap_or(input.len());
11 std::str::from_utf8(&input[0..nul_index]).map_err(Into::into)
12}