MCPcopy Create free account
hub / github.com/SeaQL/FireDBG.for.Rust / get_cstring

Function get_cstring

codelldb/adapter/crates/lldb/src/strings.rs:49–89  ·  view source on GitHub ↗

Extract CString from an API that takes pointer to a buffer and max length and returns the number of bytes stored or required to stotre the entire string.

(f: F)

Source from the content-addressed store, hash-verified

47/// Extract CString from an API that takes pointer to a buffer and max length and
48/// returns the number of bytes stored or required to stotre the entire string.
49pub(crate) fn get_cstring<F>(f: F) -> CString
50where
51 F: Fn(*mut c_char, usize) -> usize,
52{
53 // Some SB API return the required size of the full string (SBThread::GetStopDescription()),
54 // while others return the number of bytes actually written into the buffer (SBFileSpec::GetPath()).
55 // In the latter case we have to grow buffer capacity in a loop until the string fits.
56 // There also seems to be a lack of consensus whether the terminating NUL should be included in the count or not...
57
58 let mut buffer = [0u8; 1024];
59 let c_ptr = buffer.as_mut_ptr() as *mut c_char;
60 let size = f(c_ptr, buffer.len());
61 assert!((size as isize) >= 0);
62 // Must have at least 1 unused byte to ensure that we've received the entire string.
63 if size < buffer.len() - 1 {
64 unsafe {
65 return CStr::from_ptr(c_ptr).to_owned();
66 }
67 }
68
69 let capacity = if size > buffer.len() {
70 size + 2
71 } else {
72 buffer.len() * 2
73 };
74 let mut buffer = Vec::with_capacity(capacity);
75 loop {
76 let c_ptr = buffer.as_mut_ptr() as *mut c_char;
77 let size = f(c_ptr, buffer.capacity());
78 assert!((size as isize) >= 0);
79 if size < buffer.capacity() - 1 {
80 unsafe {
81 let s = CStr::from_ptr(c_ptr); // Count bytes to NUL
82 buffer.set_len(s.to_bytes().len());
83 return CString::from_vec_unchecked(buffer);
84 };
85 }
86 let capacity = buffer.capacity() * 2;
87 buffer.reserve(capacity);
88 }
89}
90
91/// Get `str` a from NUL-terminated string pointer. If the pointer is null, returns "".
92pub(crate) unsafe fn get_str<'a>(ptr: *const c_char) -> &'a str {

Callers 2

pathMethod · 0.85
stop_descriptionMethod · 0.85

Calls 2

to_bytesMethod · 0.80
lenMethod · 0.45

Tested by 1

pathMethod · 0.68