1 // Copyright (C) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 use std::ffi::{c_char, CString}; 15 16 /// Translate a &str to &[c_char; N]. trans_slice_to_array(src: &str, dest: &mut [u8])17pub fn trans_slice_to_array(src: &str, dest: &mut [u8]) { 18 let name = CString::new(src).unwrap(); 19 let name = name.to_bytes(); 20 let name_len = name.len(); 21 let end = if name_len <= dest.len() { 22 name_len 23 } else { 24 dest.len() 25 }; 26 dest[..end].copy_from_slice(&name[..end]) 27 } 28 29 /// recycle CString as raw pointer. 30 /// 31 /// # Safety 32 /// 33 /// The memory which this pointer point to is allocated in rust end, risk under 34 /// control 35 #[allow(dead_code)] free_allocated_str(ptr: *mut c_char)36pub fn free_allocated_str(ptr: *mut c_char) { 37 if ptr.is_null() { 38 return; 39 } 40 unsafe { 41 let _ = CString::from_raw(ptr); 42 } 43 } 44