Skip to content

Commit e91556a

Browse files
committed
feat: allow creating ngx_str_t from a byte slice
There's no guarantee we'll be working with a valid UTF-8 data.
1 parent 8fac2d5 commit e91556a

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

nginx-sys/src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@ mod bindings {
4949
#[doc(no_inline)]
5050
pub use bindings::*;
5151

52+
/// Convert a byte slice to a raw pointer (`*mut u_char`) allocated in the given nginx memory pool.
53+
///
54+
/// # Safety
55+
///
56+
/// The caller must provide a valid pointer to the memory pool.
57+
pub unsafe fn bytes_to_uchar(pool: *mut ngx_pool_t, data: &[u8]) -> Option<*mut u_char> {
58+
let ptr: *mut u_char = ngx_pnalloc(pool, data.len()) as _;
59+
if ptr.is_null() {
60+
return None;
61+
}
62+
copy_nonoverlapping(data.as_ptr(), ptr, data.len());
63+
Some(ptr)
64+
}
65+
5266
/// Convert a string slice (`&str`) to a raw pointer (`*mut u_char`) allocated in the given nginx memory pool.
5367
///
5468
/// # Arguments
@@ -70,6 +84,7 @@ pub use bindings::*;
7084
/// ```
7185
pub unsafe fn str_to_uchar(pool: *mut ngx_pool_t, data: &str) -> *mut u_char {
7286
let ptr: *mut u_char = ngx_pnalloc(pool, data.len()) as _;
87+
debug_assert!(!ptr.is_null());
7388
copy_nonoverlapping(data.as_ptr(), ptr, data.len());
7489
ptr
7590
}
@@ -121,6 +136,15 @@ impl ngx_str_t {
121136
std::str::from_utf8(self.as_bytes()).unwrap()
122137
}
123138

139+
/// Create an `ngx_str_t` instance from a byte slice.
140+
///
141+
/// # Safety
142+
///
143+
/// The caller must provide a valid pointer to a memory pool.
144+
pub unsafe fn from_bytes(pool: *mut ngx_pool_t, src: &[u8]) -> Option<Self> {
145+
bytes_to_uchar(pool, src).map(|data| Self { data, len: src.len() })
146+
}
147+
124148
/// Create an `ngx_str_t` instance from a `String`.
125149
///
126150
/// # Arguments

0 commit comments

Comments
 (0)