Skip to content

Commit 5331d63

Browse files
committed
refactor: overlook pool methods
1 parent 3386464 commit 5331d63

File tree

7 files changed

+71
-112
lines changed

7 files changed

+71
-112
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::Status::NGX_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::Status::NGX_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: 26 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
use std::ffi::{c_char, c_void};
1010
use std::mem;
1111

12-
use ngx::core::{Pool, Status};
12+
use ngx::core::{
13+
ngx_make_result, NgxError, Pool, Status, NGX_CONF_ERROR, NGX_CONF_OK, NGX_RES_ERROR, NGX_RES_OK,
14+
};
1315
use ngx::ffi::{
1416
ngx_atoi, ngx_command_t, ngx_conf_t, ngx_connection_t, ngx_event_free_peer_pt,
1517
ngx_event_get_peer_pt, ngx_http_module_t, ngx_http_upstream_init_peer_pt,
@@ -120,44 +122,34 @@ http_upstream_init_peer_pt!(
120122
|request: &mut Request, us: *mut ngx_http_upstream_srv_conf_t| {
121123
ngx_log_debug_http!(request, "CUSTOM UPSTREAM request peer init");
122124

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

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

135131
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;
132+
if unsafe { ngx_make_result(original_init_peer(request.into(), us)) != NGX_RES_OK } {
133+
return NGX_RES_ERROR;
138134
}
139135

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();
136+
let upstream_ptr = request.upstream().ok_or(NgxError {})?;
145137

146138
unsafe {
147139
(*hcpd).conf = Some(hccf);
148-
(*hcpd).upstream = maybe_upstream;
140+
(*hcpd).upstream = Some(upstream_ptr);
149141
(*hcpd).data = (*upstream_ptr).peer.data;
150142
(*hcpd).client_connection = Some(request.connection());
151143
(*hcpd).original_get_peer = (*upstream_ptr).peer.get;
152144
(*hcpd).original_free_peer = (*upstream_ptr).peer.free;
153145

154-
(*upstream_ptr).peer.data = hcpd as *mut c_void;
146+
(*upstream_ptr).peer.data = hcpd as _;
155147
(*upstream_ptr).peer.get = Some(ngx_http_upstream_get_custom_peer);
156148
(*upstream_ptr).peer.free = Some(ngx_http_upstream_free_custom_peer);
157149
}
158150

159151
ngx_log_debug_http!(request, "CUSTOM UPSTREAM end request peer init");
160-
Status::NGX_OK
152+
NGX_RES_OK
161153
}
162154
);
163155

@@ -280,7 +272,7 @@ unsafe extern "C" fn ngx_http_upstream_commands_set_custom(
280272
value,
281273
&(*cmd).name
282274
);
283-
return ngx::core::NGX_CONF_ERROR;
275+
return NGX_CONF_ERROR;
284276
}
285277
ccf.max = n as u32;
286278
}
@@ -297,7 +289,7 @@ unsafe extern "C" fn ngx_http_upstream_commands_set_custom(
297289

298290
ngx_log_debug_mask!(DebugMask::Http, cf.log, "CUSTOM UPSTREAM end module init");
299291

300-
ngx::core::NGX_CONF_OK
292+
NGX_CONF_OK
301293
}
302294

303295
// The upstream module.
@@ -312,24 +304,25 @@ impl HttpModule for Module {
312304

313305
unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void {
314306
let pool = Pool::from_ngx_pool((*cf).pool);
315-
let conf = pool.alloc_type::<SrvConfig>();
316-
if conf.is_null() {
307+
308+
if let Ok(mut conf) = pool.allocate_type::<SrvConfig>() {
309+
unsafe {
310+
conf.as_mut().max = NGX_CONF_UNSET as u32;
311+
}
312+
ngx_log_debug_mask!(
313+
DebugMask::Http,
314+
(*cf).log,
315+
"CUSTOM UPSTREAM end create_srv_conf"
316+
);
317+
conf.as_ptr() as _
318+
} else {
317319
ngx_conf_log_error!(
318320
NGX_LOG_EMERG,
319321
cf,
320322
"CUSTOM UPSTREAM could not allocate memory for config"
321323
);
322-
return std::ptr::null_mut();
324+
std::ptr::null_mut()
323325
}
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
333326
}
334327
}
335328

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::ffi::NGX_ERROR as _, |code| code)
2424
}
2525
};
2626
}

0 commit comments

Comments
 (0)