Skip to content

Commit

Permalink
fix: replace std to core and add config out
Browse files Browse the repository at this point in the history
  • Loading branch information
JyJyJcr committed Jan 2, 2025
1 parent 0c0e735 commit 98cb85d
Show file tree
Hide file tree
Showing 12 changed files with 81 additions and 55 deletions.
1 change: 1 addition & 0 deletions nginx-sys/build/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ fn generate_binding(nginx_build_dir: PathBuf) {
.header("build/wrapper.h")
.clang_args(clang_args)
.layout_tests(false)
.use_core()
.generate()
.expect("Unable to generate bindings");

Expand Down
43 changes: 27 additions & 16 deletions nginx-sys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
#![no_std]

use std::fmt;
use std::ptr::copy_nonoverlapping;
use std::slice;
use core::fmt;
use core::ptr::copy_nonoverlapping;
use core::slice;

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::string::{FromUtf8Error, String};
#[cfg(feature = "std")]
use std::string::{FromUtf8Error, String};

#[doc(hidden)]
mod bindings {
Expand Down Expand Up @@ -104,7 +110,7 @@ impl ngx_str_t {
/// # Returns
/// A string slice (`&str`) representing the nginx string.
pub fn to_str(&self) -> &str {
std::str::from_utf8(self.as_bytes()).unwrap()
core::str::from_utf8(self.as_bytes()).unwrap()
}

/// Create an `ngx_str_t` instance from a byte slice.
Expand All @@ -130,6 +136,7 @@ impl ngx_str_t {
///
/// # Returns
/// An `ngx_str_t` instance representing the given `String`.
#[cfg(feature = "alloc")]
pub unsafe fn from_string(pool: *mut ngx_pool_t, data: String) -> Self {
ngx_str_t {
data: str_to_uchar(pool, data.as_str()),
Expand Down Expand Up @@ -168,26 +175,29 @@ impl From<ngx_str_t> for &[u8] {
}
}

impl TryFrom<ngx_str_t> for String {
type Error = std::string::FromUtf8Error;

fn try_from(s: ngx_str_t) -> Result<Self, Self::Error> {
let bytes: &[u8] = s.into();
String::from_utf8(bytes.into())
}
}

impl fmt::Display for ngx_str_t {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", String::from_utf8_lossy((*self).into()))
// The implementation is similar to an inlined `String::from_utf8_lossy`, with two
// important differences:
//
// - it writes directly to the Formatter instead of allocating a temporary String
// - invalid sequences are represented as escaped individual bytes
for chunk in self.as_bytes().utf8_chunks() {
f.write_str(chunk.valid())?;
for byte in chunk.invalid() {
f.write_str("\\x")?;
fmt::LowerHex::fmt(byte, f)?;
}
}
Ok(())
}
}

impl TryFrom<ngx_str_t> for &str {
type Error = std::str::Utf8Error;
type Error = core::str::Utf8Error;

fn try_from(s: ngx_str_t) -> Result<Self, Self::Error> {
std::str::from_utf8(s.into())
core::str::from_utf8(s.into())
}
}

Expand Down Expand Up @@ -218,6 +228,7 @@ impl TryFrom<ngx_str_t> for &str {
/// let result = add_to_ngx_table(table, pool, key, value);
/// # }
/// ```
#[cfg(feature = "alloc")]
pub unsafe fn add_to_ngx_table(
table: *mut ngx_table_elt_t,
pool: *mut ngx_pool_t,
Expand Down
2 changes: 1 addition & 1 deletion src/core/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::slice;
use core::slice;

use crate::ffi::*;

Expand Down
2 changes: 1 addition & 1 deletion src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ macro_rules! ngx_null_command {
set: None,
conf: 0,
offset: 0,
post: ::std::ptr::null_mut(),
post: ::core::ptr::null_mut(),
}
};
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/pool.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::ffi::c_void;
use std::{mem, ptr};
use core::ffi::c_void;
use core::{mem, ptr};

use crate::core::buffer::{Buffer, MemoryBuffer, TemporaryBuffer};
use crate::ffi::*;
Expand Down
2 changes: 1 addition & 1 deletion src/core/status.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt;
use core::fmt;

use crate::ffi::*;

Expand Down
16 changes: 9 additions & 7 deletions src/core/string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::borrow::Cow;
use std::slice;
use std::str::{self, Utf8Error};
use core::slice;
use core::str::{self, Utf8Error};

use crate::ffi::*;

Expand All @@ -27,7 +26,7 @@ macro_rules! ngx_null_string {
() => {
$crate::ffi::ngx_str_t {
len: 0,
data: ::std::ptr::null_mut(),
data: ::core::ptr::null_mut(),
}
};
}
Expand Down Expand Up @@ -61,11 +60,14 @@ impl NgxStr {
str::from_utf8(self.as_bytes())
}

/// Converts an [`NgxStr`] into a [`Cow<str>`], replacing invalid UTF-8 sequences.
/// Converts an [`NgxStr`] into a [`std::borrow::Cow<str>`], replacing invalid UTF-8 sequences.
///
/// See [`String::from_utf8_lossy`].
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(self.as_bytes())
///
/// This module is temporally available only with `std` feature.
#[cfg(feature = "std")]
pub fn to_string_lossy(&self) -> std::borrow::Cow<str> {
std::string::String::from_utf8_lossy(self.as_bytes())
}

/// Returns `true` if the [`NgxStr`] is empty, otherwise `false`.
Expand Down
2 changes: 1 addition & 1 deletion src/http/conf.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::ffi::c_void;
use core::ffi::c_void;

use crate::ffi::*;

Expand Down
10 changes: 6 additions & 4 deletions src/http/module.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::ffi::{c_char, c_void};
use std::ptr;
use core::ffi::{c_char, c_void};
use core::fmt;
use core::ptr;

use crate::core::NGX_CONF_ERROR;
use crate::core::*;
Expand All @@ -12,10 +13,11 @@ pub enum MergeConfigError {
NoValue,
}

#[cfg(feature = "std")]
impl std::error::Error for MergeConfigError {}

impl std::fmt::Display for MergeConfigError {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
impl fmt::Display for MergeConfigError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
MergeConfigError::NoValue => "no value".fmt(fmt),
}
Expand Down
28 changes: 15 additions & 13 deletions src/http/request.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::error::Error;
use std::ffi::c_void;
use std::fmt;
use std::str::FromStr;
use core::ffi::c_void;
use core::fmt;
use core::str::FromStr;

use crate::core::*;
use crate::ffi::*;
Expand Down Expand Up @@ -30,7 +29,7 @@ macro_rules! http_subrequest_handler {
( $name: ident, $handler: expr ) => {
unsafe extern "C" fn $name(
r: *mut $crate::ffi::ngx_http_request_t,
data: *mut ::std::ffi::c_void,
data: *mut ::core::ffi::c_void,
rc: $crate::ffi::ngx_int_t,
) -> $crate::ffi::ngx_int_t {
$handler(r, data, rc)
Expand Down Expand Up @@ -116,7 +115,7 @@ impl Request {
/// Is this the main request (as opposed to a subrequest)?
pub fn is_main(&self) -> bool {
let main = self.0.main.cast();
std::ptr::eq(self, main)
core::ptr::eq(self, main)
}

/// Request pool.
Expand Down Expand Up @@ -263,6 +262,7 @@ impl Request {
/// Add header to the `headers_in` object.
///
/// See <https://nginx.org/en/docs/dev/development_guide.html#http_request>
#[cfg(feature = "alloc")]
pub fn add_header_in(&mut self, key: &str, value: &str) -> Option<()> {
let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.0.headers_in.headers) as _ };
unsafe { add_to_ngx_table(table, self.0.pool, key, value) }
Expand All @@ -271,6 +271,7 @@ impl Request {
/// Add header to the `headers_out` object.
///
/// See <https://nginx.org/en/docs/dev/development_guide.html#http_request>
#[cfg(feature = "alloc")]
pub fn add_header_out(&mut self, key: &str, value: &str) -> Option<()> {
let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.0.headers_out.headers) as _ };
unsafe { add_to_ngx_table(table, self.0.pool, key, value) }
Expand Down Expand Up @@ -337,7 +338,7 @@ impl Request {
ngx_http_internal_redirect(
(self as *const Request as *mut Request).cast(),
uri_ptr,
std::ptr::null_mut(),
core::ptr::null_mut(),
);
}
}
Expand All @@ -354,7 +355,7 @@ impl Request {
let uri_ptr = unsafe { &mut ngx_str_t::from_str(self.0.pool, uri) as *mut _ };
// -------------
// allocate memory and set values for ngx_http_post_subrequest_t
let sub_ptr = self.pool().alloc(std::mem::size_of::<ngx_http_post_subrequest_t>());
let sub_ptr = self.pool().alloc(core::mem::size_of::<ngx_http_post_subrequest_t>());

// assert!(sub_ptr.is_null());
let post_subreq = sub_ptr as *const ngx_http_post_subrequest_t as *mut ngx_http_post_subrequest_t;
Expand All @@ -364,12 +365,12 @@ impl Request {
}
// -------------

let mut psr: *mut ngx_http_request_t = std::ptr::null_mut();
let mut psr: *mut ngx_http_request_t = core::ptr::null_mut();
let r = unsafe {
ngx_http_subrequest(
(self as *const Request as *mut Request).cast(),
uri_ptr,
std::ptr::null_mut(),
core::ptr::null_mut(),
&mut psr as *mut _,
sub_ptr as *mut _,
NGX_HTTP_SUBREQUEST_WAITED as _,
Expand All @@ -383,7 +384,7 @@ impl Request {
* allocate fake request body to avoid attempts to read it and to make
* sure real body file (if already read) won't be closed by upstream
*/
sr.request_body = self.pool().alloc(std::mem::size_of::<ngx_http_request_body_t>()) as *mut _;
sr.request_body = self.pool().alloc(core::mem::size_of::<ngx_http_request_body_t>()) as *mut _;

if sr.request_body.is_null() {
return Status::NGX_ERROR;
Expand Down Expand Up @@ -422,7 +423,7 @@ impl fmt::Debug for Request {

/// Iterator for [`ngx_list_t`] types.
///
/// Implementes the std::iter::Iterator trait.
/// Implementes the core::iter::Iterator trait.
pub struct NgxListIterator {
done: bool,
part: *const ngx_list_part_t,
Expand Down Expand Up @@ -711,7 +712,8 @@ impl fmt::Display for InvalidMethod {
}
}

impl Error for InvalidMethod {}
#[cfg(feature = "std")]
impl std::error::Error for InvalidMethod {}

#[derive(Clone, PartialEq, Eq, Hash)]
enum MethodInner {
Expand Down
6 changes: 3 additions & 3 deletions src/http/status.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::error::Error;
use std::fmt;
use core::fmt;

use crate::core::Status;
use crate::ffi::*;
Expand Down Expand Up @@ -29,7 +28,8 @@ impl fmt::Display for InvalidHTTPStatusCode {
}
}

impl Error for InvalidHTTPStatusCode {}
#[cfg(feature = "std")]
impl std::error::Error for InvalidHTTPStatusCode {}

impl From<HTTPStatus> for Status {
fn from(val: HTTPStatus) -> Self {
Expand Down
20 changes: 14 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@
//! # now you can use dynamic modules with the NGINX
//! ```
// support both std and no_std
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
#[cfg(all(not(feature = "std"), feature = "alloc"))]
extern crate alloc;

/// The core module.
///
/// This module provides fundamental utilities needed to interface with many NGINX primitives.
Expand All @@ -54,6 +59,9 @@ pub mod http;
/// The log module.
///
/// This module provides an interface into the NGINX logger framework.
///
/// This module is temporally available only with `std` feature.
#[cfg(feature = "std")]
pub mod log;

/// Define modules exported by this library.
Expand All @@ -67,20 +75,20 @@ macro_rules! ngx_modules {
#[allow(non_upper_case_globals)]
pub static mut ngx_modules: [*const $crate::ffi::ngx_module_t; $crate::count!($( $mod, )+) + 1] = [
$( unsafe { &$mod } as *const $crate::ffi::ngx_module_t, )+
::std::ptr::null()
::core::ptr::null()
];

#[no_mangle]
#[allow(non_upper_case_globals)]
pub static mut ngx_module_names: [*const ::std::ffi::c_char; $crate::count!($( $mod, )+) + 1] = [
$( concat!(stringify!($mod), "\0").as_ptr() as *const ::std::ffi::c_char, )+
::std::ptr::null()
pub static mut ngx_module_names: [*const ::core::ffi::c_char; $crate::count!($( $mod, )+) + 1] = [
$( concat!(stringify!($mod), "\0").as_ptr() as *const ::core::ffi::c_char, )+
::core::ptr::null()
];

#[no_mangle]
#[allow(non_upper_case_globals)]
pub static mut ngx_module_order: [*const ::std::ffi::c_char; 1] = [
::std::ptr::null()
pub static mut ngx_module_order: [*const ::core::ffi::c_char; 1] = [
::core::ptr::null()
];
};
}
Expand Down

0 comments on commit 98cb85d

Please sign in to comment.