Skip to content

Commit 7f6e4e6

Browse files
committed
refactor: overlook pool methods
1 parent e95e2b8 commit 7f6e4e6

File tree

5 files changed

+61
-102
lines changed

5 files changed

+61
-102
lines changed

examples/httporigdst.rs

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,31 +19,13 @@ 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) -> core::NgxResult {
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;
26+
self.orig_dst_port = unsafe { ngx_str_t::from_str(pool.as_ptr(), &port_str) };
4527

46-
core::Status::NGX_OK
28+
Ok(core::Status::NGX_OK.into())
4729
}
4830

4931
pub unsafe fn bind_addr(&self, v: *mut ngx_variable_value_t) {
@@ -226,7 +208,7 @@ http_variable_get!(
226208
ip,
227209
port,
228210
);
229-
(*new_ctx).save(&ip, port, &request.pool());
211+
(*new_ctx).save(&ip, port, &request.pool())?;
230212
(*new_ctx).bind_addr(v);
231213
request
232214
.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module));
@@ -273,7 +255,7 @@ http_variable_get!(
273255
ip,
274256
port,
275257
);
276-
(*new_ctx).save(&ip, port, &request.pool());
258+
(*new_ctx).save(&ip, port, &request.pool())?;
277259
(*new_ctx).bind_port(v);
278260
request
279261
.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module));

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: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -120,44 +120,34 @@ 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();
136130
if unsafe { original_init_peer(request.into(), us) != Status::NGX_OK.into() } {
137-
return Status::NGX_ERROR;
131+
return Status::NGX_ERROR.into();
138132
}
139133

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();
134+
let upstream_ptr = request.upstream().ok_or(ngx::core::NgxError {})?;
145135

146136
unsafe {
147137
(*hcpd).conf = Some(hccf);
148-
(*hcpd).upstream = maybe_upstream;
138+
(*hcpd).upstream = Some(upstream_ptr);
149139
(*hcpd).data = (*upstream_ptr).peer.data;
150140
(*hcpd).client_connection = Some(request.connection());
151141
(*hcpd).original_get_peer = (*upstream_ptr).peer.get;
152142
(*hcpd).original_free_peer = (*upstream_ptr).peer.free;
153143

154-
(*upstream_ptr).peer.data = hcpd as *mut c_void;
144+
(*upstream_ptr).peer.data = hcpd as _;
155145
(*upstream_ptr).peer.get = Some(ngx_http_upstream_get_custom_peer);
156146
(*upstream_ptr).peer.free = Some(ngx_http_upstream_free_custom_peer);
157147
}
158148

159149
ngx_log_debug_http!(request, "CUSTOM UPSTREAM end request peer init");
160-
Status::NGX_OK
150+
Status::NGX_OK.into()
161151
}
162152
);
163153

@@ -312,24 +302,25 @@ impl HttpModule for Module {
312302

313303
unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void {
314304
let pool = Pool::from_ngx_pool((*cf).pool);
315-
let conf = pool.alloc_type::<SrvConfig>();
316-
if conf.is_null() {
305+
306+
if let Ok(mut conf) = pool.allocate_type::<SrvConfig>() {
307+
unsafe {
308+
conf.as_mut().max = NGX_CONF_UNSET as u32;
309+
}
310+
ngx_log_debug_mask!(
311+
DebugMask::Http,
312+
(*cf).log,
313+
"CUSTOM UPSTREAM end create_srv_conf"
314+
);
315+
conf.as_ptr() as _
316+
} else {
317317
ngx_conf_log_error!(
318318
NGX_LOG_EMERG,
319319
cf,
320320
"CUSTOM UPSTREAM could not allocate memory for config"
321321
);
322-
return std::ptr::null_mut();
322+
std::ptr::null_mut()
323323
}
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
333324
}
334325
}
335326

src/core/pool.rs

Lines changed: 29 additions & 43 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,44 +226,6 @@ 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
///
@@ -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/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)