summaryrefslogtreecommitdiff
path: root/rust/src/string.rs
diff options
context:
space:
mode:
authorMason Reed <mason@vector35.com>2025-05-03 23:15:17 -0400
committerMason Reed <35282038+emesare@users.noreply.github.com>2025-05-12 17:45:24 -0400
commit6264254065bbae9d89f51cf3330379b7ace09592 (patch)
tree9ece1d1739215c2faef2d808ef4fdc019ad527fa /rust/src/string.rs
parentc3fdda9727f5507818e3f55576ad32215a22b0f9 (diff)
[Rust] Return `String` instead of `BnString` for cases where lossy conversion can be tolerated
Still need to go and audit all usage, but realistically the most important places to give the user control are with symbols, where the data can come from non utf8 sources This is still incomplete, I just looked for usage of -> BnString so any other variant was omitted.
Diffstat (limited to 'rust/src/string.rs')
-rw-r--r--rust/src/string.rs60
1 files changed, 36 insertions, 24 deletions
diff --git a/rust/src/string.rs b/rust/src/string.rs
index f9224851..3cdbf384 100644
--- a/rust/src/string.rs
+++ b/rust/src/string.rs
@@ -69,10 +69,25 @@ impl BnString {
}
}
+ /// Take an owned core string and convert it to [`String`].
+ ///
+ /// This expects the passed raw string to be owned, as in, freed by us.
+ pub unsafe fn into_string(raw: *mut c_char) -> String {
+ Self::from_raw(raw).to_string()
+ }
+
/// Construct a BnString from an owned const char* allocated by BNAllocString
pub(crate) unsafe fn from_raw(raw: *mut c_char) -> Self {
Self { raw }
}
+
+ /// Free a raw string allocated by BNAllocString.
+ pub(crate) unsafe fn free_raw(raw: *mut c_char) {
+ use binaryninjacore_sys::BNFreeString;
+ if !raw.is_null() {
+ BNFreeString(raw);
+ }
+ }
/// Consumes the `BnString`, returning a raw pointer to the string.
///
@@ -87,34 +102,11 @@ impl BnString {
mem::forget(value);
res
}
-
- pub fn as_str(&self) -> &str {
- unsafe { CStr::from_ptr(self.raw).to_str().unwrap() }
- }
-
- pub fn as_bytes(&self) -> &[u8] {
- self.as_str().as_bytes()
- }
-
- pub fn as_bytes_with_null(&self) -> &[u8] {
- self.deref().to_bytes()
- }
-
- pub fn len(&self) -> usize {
- self.as_str().len()
- }
-
- pub fn is_empty(&self) -> bool {
- self.as_str().is_empty()
- }
}
impl Drop for BnString {
fn drop(&mut self) {
- use binaryninjacore_sys::BNFreeString;
- unsafe {
- BNFreeString(self.raw);
- }
+ unsafe { BnString::free_raw(self.raw) };
}
}
@@ -137,6 +129,18 @@ impl Deref for BnString {
}
}
+impl From<String> for BnString {
+ fn from(s: String) -> Self {
+ Self::new(s)
+ }
+}
+
+impl From<&str> for BnString {
+ fn from(s: &str) -> Self {
+ Self::new(s)
+ }
+}
+
impl AsRef<[u8]> for BnString {
fn as_ref(&self) -> &[u8] {
self.to_bytes_with_nul()
@@ -208,6 +212,14 @@ unsafe impl BnStrCompatible for BnString {
}
}
+unsafe impl BnStrCompatible for &BnString {
+ type Result = Self;
+
+ fn into_bytes_with_nul(self) -> Self::Result {
+ self
+ }
+}
+
unsafe impl BnStrCompatible for CString {
type Result = Vec<u8>;