Skip to content

Commit e74e21b

Browse files
committed
refactor: overlook pool methods
1 parent a070577 commit e74e21b

File tree

7 files changed

+69
-109
lines changed

7 files changed

+69
-109
lines changed

examples/async.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ http_request_handler!(async_access_handler, |request: &mut http::Request| {
156156
return core::NGX_RES_OK;
157157
}
158158

159-
let ctx = request.pool().allocate(RequestCTX::default());
159+
let ctx = request.pool().alloc_with_cleanup(RequestCTX::default());
160160
if ctx.is_null() {
161161
return core::NGX_RES_ERROR;
162162
}

examples/httporigdst.rs

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,11 @@ struct NgxHttpOrigDstCtx {
1919
}
2020

2121
impl NgxHttpOrigDstCtx {
22-
pub fn save(&mut self, addr: &str, port: in_port_t, pool: &core::Pool) -> core::Status {
23-
let addr_data = pool.alloc_unaligned(addr.len());
24-
if addr_data.is_null() {
25-
return core::Status::NGX_ERROR;
26-
}
27-
unsafe { libc::memcpy(addr_data, addr.as_ptr() as *const c_void, addr.len()) };
28-
self.orig_dst_addr.len = addr.len();
29-
self.orig_dst_addr.data = addr_data as *mut u8;
22+
pub fn save(&mut self, addr: &str, port: in_port_t, pool: &core::Pool) {
23+
self.orig_dst_addr = unsafe { ngx_str_t::from_str(pool.as_ptr(), addr) };
3024

3125
let port_str = port.to_string();
32-
let port_data = pool.alloc_unaligned(port_str.len());
33-
if port_data.is_null() {
34-
return core::Status::NGX_ERROR;
35-
}
36-
unsafe {
37-
libc::memcpy(
38-
port_data,
39-
port_str.as_bytes().as_ptr() as *const c_void,
40-
port_str.len(),
41-
)
42-
};
43-
self.orig_dst_port.len = port_str.len();
44-
self.orig_dst_port.data = port_data as *mut u8;
45-
46-
core::Status::NGX_OK
26+
self.orig_dst_port = unsafe { ngx_str_t::from_str(pool.as_ptr(), &port_str) };
4727
}
4828

4929
pub unsafe fn bind_addr(&self, v: *mut ngx_variable_value_t) {
@@ -214,7 +194,7 @@ http_variable_get!(
214194
// set context
215195
let new_ctx = request
216196
.pool()
217-
.allocate::<NgxHttpOrigDstCtx>(Default::default());
197+
.alloc_with_cleanup::<NgxHttpOrigDstCtx>(Default::default());
218198

219199
if new_ctx.is_null() {
220200
return core::NGX_RES_ERROR;
@@ -261,7 +241,7 @@ http_variable_get!(
261241
// set context
262242
let new_ctx = request
263243
.pool()
264-
.allocate::<NgxHttpOrigDstCtx>(Default::default());
244+
.alloc_with_cleanup::<NgxHttpOrigDstCtx>(Default::default());
265245

266246
if new_ctx.is_null() {
267247
return core::NGX_RES_ERROR;

examples/shared_dict.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -200,10 +200,10 @@ extern "C" fn ngx_http_shared_dict_add_variable(
200200
let cf = unsafe { cf.as_mut().unwrap() };
201201
let pool = unsafe { Pool::from_ngx_pool(cf.pool) };
202202

203-
let key = pool.calloc_type::<ngx_http_complex_value_t>();
204-
if key.is_null() {
205-
return NGX_CONF_ERROR;
206-
}
203+
let key = match pool.allocate_type_zeroed::<ngx_http_complex_value_t>() {
204+
Ok(p) => p.as_ptr(),
205+
Err(_) => return NGX_CONF_ERROR,
206+
};
207207

208208
// SAFETY:
209209
// - `cf.args` is guaranteed to be a pointer to an array with 3 elements (NGX_CONF_TAKE2).

examples/upstream.rs

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -120,44 +120,37 @@ http_upstream_init_peer_pt!(
120120
|request: &mut Request, us: *mut ngx_http_upstream_srv_conf_t| {
121121
ngx_log_debug_http!(request, "CUSTOM UPSTREAM request peer init");
122122

123-
let hcpd = request.pool().alloc_type::<UpstreamPeerData>();
124-
if hcpd.is_null() {
125-
return Status::NGX_ERROR;
126-
}
123+
let hcpd = request.pool().allocate_type::<UpstreamPeerData>()?.as_ptr();
127124

128125
// SAFETY: this function is called with non-NULL uf always
129126
let us = unsafe { &mut *us };
130-
let hccf = match Module::server_conf(us) {
131-
Some(x) => x,
132-
None => return Status::NGX_ERROR,
133-
};
127+
let hccf = Module::server_conf(us).ok_or(ngx::core::NgxError {})?;
134128

135129
let original_init_peer = hccf.original_init_peer.unwrap();
136-
if unsafe { original_init_peer(request.into(), us) != Status::NGX_OK.into() } {
137-
return Status::NGX_ERROR;
130+
if unsafe {
131+
ngx::core::ngx_make_result(original_init_peer(request.into(), us))
132+
!= ngx::core::NGX_RES_OK
133+
} {
134+
return ngx::core::NGX_RES_ERROR;
138135
}
139136

140-
let maybe_upstream = request.upstream();
141-
if maybe_upstream.is_none() {
142-
return Status::NGX_ERROR;
143-
}
144-
let upstream_ptr = maybe_upstream.unwrap();
137+
let upstream_ptr = request.upstream().ok_or(ngx::core::NgxError {})?;
145138

146139
unsafe {
147140
(*hcpd).conf = Some(hccf);
148-
(*hcpd).upstream = maybe_upstream;
141+
(*hcpd).upstream = Some(upstream_ptr);
149142
(*hcpd).data = (*upstream_ptr).peer.data;
150143
(*hcpd).client_connection = Some(request.connection());
151144
(*hcpd).original_get_peer = (*upstream_ptr).peer.get;
152145
(*hcpd).original_free_peer = (*upstream_ptr).peer.free;
153146

154-
(*upstream_ptr).peer.data = hcpd as *mut c_void;
147+
(*upstream_ptr).peer.data = hcpd as _;
155148
(*upstream_ptr).peer.get = Some(ngx_http_upstream_get_custom_peer);
156149
(*upstream_ptr).peer.free = Some(ngx_http_upstream_free_custom_peer);
157150
}
158151

159152
ngx_log_debug_http!(request, "CUSTOM UPSTREAM end request peer init");
160-
Status::NGX_OK
153+
ngx::core::NGX_RES_OK
161154
}
162155
);
163156

@@ -312,24 +305,25 @@ impl HttpModule for Module {
312305

313306
unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void {
314307
let pool = Pool::from_ngx_pool((*cf).pool);
315-
let conf = pool.alloc_type::<SrvConfig>();
316-
if conf.is_null() {
308+
309+
if let Ok(mut conf) = pool.allocate_type::<SrvConfig>() {
310+
unsafe {
311+
conf.as_mut().max = NGX_CONF_UNSET as u32;
312+
}
313+
ngx_log_debug_mask!(
314+
DebugMask::Http,
315+
(*cf).log,
316+
"CUSTOM UPSTREAM end create_srv_conf"
317+
);
318+
conf.as_ptr() as _
319+
} else {
317320
ngx_conf_log_error!(
318321
NGX_LOG_EMERG,
319322
cf,
320323
"CUSTOM UPSTREAM could not allocate memory for config"
321324
);
322-
return std::ptr::null_mut();
325+
std::ptr::null_mut()
323326
}
324-
325-
(*conf).max = NGX_CONF_UNSET as u32;
326-
327-
ngx_log_debug_mask!(
328-
DebugMask::Http,
329-
(*cf).log,
330-
"CUSTOM UPSTREAM end create_srv_conf"
331-
);
332-
conf as *mut c_void
333327
}
334328
}
335329

src/core/pool.rs

Lines changed: 30 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use core::mem;
44
use core::ptr::{self, NonNull};
55

66
use nginx_sys::{
7-
ngx_buf_t, ngx_create_temp_buf, ngx_palloc, ngx_pcalloc, ngx_pfree, ngx_pmemalign, ngx_pnalloc,
7+
ngx_buf_t, ngx_create_temp_buf, ngx_palloc, ngx_pfree, ngx_pmemalign, ngx_pnalloc,
88
ngx_pool_cleanup_add, ngx_pool_t, NGX_ALIGNMENT,
99
};
1010

@@ -183,10 +183,7 @@ impl Pool {
183183
/// Returns `Some(MemoryBuffer)` if the buffer is successfully created, or `None` if allocation
184184
/// fails.
185185
pub fn create_buffer_from_static_str(&self, str: &'static str) -> Option<MemoryBuffer> {
186-
let buf = self.calloc_type::<ngx_buf_t>();
187-
if buf.is_null() {
188-
return None;
189-
}
186+
let buf = self.allocate(Layout::new::<ngx_buf_t>()).ok()?.as_ptr() as *mut ngx_buf_t;
190187

191188
// We cast away const, but buffers with the memory flag are read-only
192189
let start = str.as_ptr() as *mut u8;
@@ -229,50 +226,12 @@ impl Pool {
229226
unsafe { ngx_palloc(self.0.as_ptr(), size) }
230227
}
231228

232-
/// Allocates memory for a type from the pool.
233-
/// The resulting pointer is aligned to a platform word size.
234-
///
235-
/// Returns a typed pointer to the allocated memory.
236-
pub fn alloc_type<T: Copy>(&self) -> *mut T {
237-
self.alloc(mem::size_of::<T>()) as *mut T
238-
}
239-
240-
/// Allocates zeroed memory from the pool of the specified size.
241-
/// The resulting pointer is aligned to a platform word size.
242-
///
243-
/// Returns a raw pointer to the allocated memory.
244-
pub fn calloc(&self, size: usize) -> *mut c_void {
245-
unsafe { ngx_pcalloc(self.0.as_ptr(), size) }
246-
}
247-
248-
/// Allocates zeroed memory for a type from the pool.
249-
/// The resulting pointer is aligned to a platform word size.
250-
///
251-
/// Returns a typed pointer to the allocated memory.
252-
pub fn calloc_type<T: Copy>(&self) -> *mut T {
253-
self.calloc(mem::size_of::<T>()) as *mut T
254-
}
255-
256-
/// Allocates unaligned memory from the pool of the specified size.
257-
///
258-
/// Returns a raw pointer to the allocated memory.
259-
pub fn alloc_unaligned(&self, size: usize) -> *mut c_void {
260-
unsafe { ngx_pnalloc(self.0.as_ptr(), size) }
261-
}
262-
263-
/// Allocates unaligned memory for a type from the pool.
264-
///
265-
/// Returns a typed pointer to the allocated memory.
266-
pub fn alloc_type_unaligned<T: Copy>(&self) -> *mut T {
267-
self.alloc_unaligned(mem::size_of::<T>()) as *mut T
268-
}
269-
270229
/// Allocates memory for a value of a specified type and adds a cleanup handler to the memory
271230
/// pool.
272231
///
273232
/// Returns a typed pointer to the allocated memory if successful, or a null pointer if
274233
/// allocation or cleanup handler addition fails.
275-
pub fn allocate<T>(&self, value: T) -> *mut T {
234+
pub fn alloc_with_cleanup<T>(&self, value: T) -> *mut T {
276235
unsafe {
277236
let p = self.alloc(mem::size_of::<T>()) as *mut T;
278237
ptr::write(p, value);
@@ -284,6 +243,33 @@ impl Pool {
284243
}
285244
}
286245

246+
/// Allocates unaligned memory from the pool of the specified size.
247+
///
248+
/// Returns Result::Ok with a typed pointer to the allocated memory if successful,
249+
/// or Result::Err(AllocError) if allocation or cleanup handler addition fails.
250+
pub fn allocate_unaligned(&self, size: usize) -> Result<NonNull<[u8]>, AllocError> {
251+
self.allocate(unsafe { Layout::from_size_align_unchecked(size, 1) })
252+
}
253+
254+
/// Allocates memory for a type from the pool.
255+
/// The resulting pointer is aligned to a platform word size.
256+
///
257+
/// Returns Result::Ok with a typed pointer to the allocated memory if successful,
258+
/// or Result::Err(AllocError) if allocation fails.
259+
pub fn allocate_type<T>(&self) -> Result<NonNull<T>, AllocError> {
260+
self.allocate(Layout::new::<T>()).map(|ptr| ptr.cast())
261+
}
262+
263+
/// Allocates zeroed memory for a type from the pool.
264+
/// The resulting pointer is aligned to a platform word size.
265+
///
266+
/// Returns Result::Ok with a typed pointer to the allocated memory if successful,
267+
/// or Result::Err(AllocError) if allocation fails.
268+
pub fn allocate_type_zeroed<T>(&self) -> Result<NonNull<T>, AllocError> {
269+
self.allocate_zeroed(Layout::new::<T>())
270+
.map(|ptr| ptr.cast())
271+
}
272+
287273
/// Resizes a memory allocation in place if possible.
288274
///
289275
/// If resizing is requested for the last allocation in the pool, it may be

src/http/module.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ pub trait HttpModule {
7878
Self::MainConf: Default,
7979
{
8080
let pool = Pool::from_ngx_pool((*cf).pool);
81-
pool.allocate::<Self::MainConf>(Default::default()) as *mut c_void
81+
pool.alloc_with_cleanup::<Self::MainConf>(Default::default()) as *mut c_void
8282
}
8383

8484
/// # Safety
@@ -103,7 +103,7 @@ pub trait HttpModule {
103103
Self::ServerConf: Default,
104104
{
105105
let pool = Pool::from_ngx_pool((*cf).pool);
106-
pool.allocate::<Self::ServerConf>(Default::default()) as *mut c_void
106+
pool.alloc_with_cleanup::<Self::ServerConf>(Default::default()) as *mut c_void
107107
}
108108

109109
/// # Safety
@@ -137,7 +137,7 @@ pub trait HttpModule {
137137
Self::LocationConf: Default,
138138
{
139139
let pool = Pool::from_ngx_pool((*cf).pool);
140-
pool.allocate::<Self::LocationConf>(Default::default()) as *mut c_void
140+
pool.alloc_with_cleanup::<Self::LocationConf>(Default::default()) as *mut c_void
141141
}
142142

143143
/// # Safety

src/http/upstream.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ macro_rules! http_upstream_init_peer_pt {
1616
r: *mut $crate::ffi::ngx_http_request_t,
1717
us: *mut $crate::ffi::ngx_http_upstream_srv_conf_t,
1818
) -> $crate::ffi::ngx_int_t {
19-
let status: $crate::core::Status = $handler(
19+
let res: $crate::core::NgxResult = $handler(
2020
unsafe { &mut $crate::http::Request::from_ngx_http_request(r) },
2121
us,
2222
);
23-
status.0
23+
res.map_or_else(|_| $crate::core::Status::NGX_ERROR.into(), |code| code)
2424
}
2525
};
2626
}

0 commit comments

Comments
 (0)