mountpoint_s3_crt/common/string.rs
1//! CRT strings are immutable bytes with no inherent encoding. Most CRT APIs use byte buffers
2//! instead, so this binding for `aws_string` is mostly for automatic memory management.
3
4use std::ptr::NonNull;
5
6use mountpoint_s3_crt_sys::*;
7
8use crate::common::allocator::Allocator;
9
10/// An immutable string holding either text or binary data.
11// We call this `AwsString` just because Rust's `String` type is in the prelude and we don't want to
12// confuse the two.
13#[derive(Debug)]
14pub struct AwsString {
15 inner: NonNull<aws_string>,
16}
17
18impl AwsString {
19 /// Create a new [AwsString] from the given Rust string. The new string will be automatically
20 /// freed when dropped.
21 pub fn from_str<S: AsRef<str>>(s: S, allocator: &Allocator) -> Self {
22 let bytes = s.as_ref().as_bytes();
23 // SAFETY: `aws_string_new_from_array` will copy the bytes out of `bytes`
24 let inner = unsafe { aws_string_new_from_array(allocator.inner.as_ptr(), bytes.as_ptr(), bytes.len()) };
25 let inner = NonNull::new(inner).expect("allocation failed");
26 Self { inner }
27 }
28
29 pub(crate) fn as_ptr(&self) -> *const aws_string {
30 self.inner.as_ptr()
31 }
32}
33
34impl Drop for AwsString {
35 fn drop(&mut self) {
36 // SAFETY: we own the underlying `aws_string`
37 unsafe {
38 aws_string_destroy(self.inner.as_ptr());
39 }
40 }
41}