rust_rsm/common/
rawstring.rs

1/*提供C格式兼容的以\0结尾的字符串的处理 */
2#![allow(non_camel_case_types)]
3#![allow(non_snake_case)]
4#![allow(non_upper_case_globals)]
5use super::*;
6//expect_max_len是指缓冲区的最大长度
7pub fn raw_strlen(str: *const u8, expect_max_len: usize) -> usize {
8    let mut len: usize = 0;
9    unsafe {
10        while *((str as usize + len) as *const u8) != 0 && len < expect_max_len {
11            len += 1;
12        }
13    }
14    len
15}
16
17//src_len是指raw buffer的最大长度,比如一个[u8,64]数组类型转换为*mut u8后,需要指明其最大长度为64,实际的字符串长度以0结尾
18pub fn array_to_string(src: *const u8, src_len: usize) -> String {
19    if src.is_null() {
20        return "".to_string()
21    }
22    let strlen = raw_strlen(src, src_len);
23    let mut buf:Vec<u8>=Vec::with_capacity(strlen+1);
24    buf.resize(strlen+1,0);
25    unsafe {        
26        std::ptr::copy(src, buf.as_mut_ptr(), strlen);
27        buf.set_len(strlen);
28    }
29  
30
31    String::from_utf8_lossy(buf.as_slice()).to_string()
32}
33
34pub fn strncpy(dst: *mut u8, len: usize, src: &String) -> *mut u8 {
35    let mut max_len = len;
36    if len > src.len() {
37        max_len = src.len();
38    }
39
40    for i in 0..max_len {
41        unsafe {
42            *((dst as usize + i) as *mut u8) = src.as_bytes()[i];
43        }
44    }
45    return dst;
46}
47
48pub fn slice_to_hex_string(v:&[u8])->String {
49    let mut s = String::with_capacity(v.len()*5);
50    for j in v {
51        s+=format!("0x{:02x} ",j).as_str();
52    }
53    s
54}
55
56pub fn unicode_str_to_string(ustr:*const u16)->String {
57    let mut raw_len = 0;
58    const MAX_STRING_LEN:usize=1024;
59    unsafe {
60    while *((ustr as usize + raw_len*2) as *const u16)!=0 && raw_len<MAX_STRING_LEN{
61        raw_len+=1;
62    }
63    //println!("utf16 string len={}",raw_len);
64    String::from_utf16_lossy(&(*(ustr as *const [u16;MAX_STRING_LEN]))[0..raw_len]).to_string()
65}
66}
67
68///将一个ansi编码的字符串拷贝到16bit unicode编码的字符串中
69pub fn ansi_str_to_unicode(ansi_str:&[u8],unicode:&mut [u16])->errcode::RESULT {
70    if unicode.len()<ansi_str.len() {
71        return errcode::ERROR_BUFFER_TOO_SMALL
72    }
73
74    for i in 0..ansi_str.len() {
75        unicode[i]=ansi_str[i] as u16;
76    }
77    errcode::RESULT_SUCCESS
78}