Skip to content

Commit

Permalink
refactor(ffi): Removed need for cbindgen type renames (hyperium#2442)
Browse files Browse the repository at this point in the history
  • Loading branch information
CfirTsabari authored Feb 23, 2021
1 parent 0b11eee commit a602808
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 57 deletions.
5 changes: 0 additions & 5 deletions capi/cbindgen.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,3 @@ documentation_style = "c"

[parse.expand]
crates = ["hyper-capi"]

[export.rename]
"Exec" = "hyper_executor"
"Io" = "hyper_io"
"Task" = "hyper_task"
10 changes: 5 additions & 5 deletions src/ffi/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::task::{Context, Poll};
use http::HeaderMap;
use libc::{c_int, size_t};

use super::task::{hyper_context, hyper_task_return_type, AsTaskType, Task};
use super::task::{hyper_context, hyper_task, hyper_task_return_type, AsTaskType};
use super::{UserDataPointer, HYPER_ITER_CONTINUE};
use crate::body::{Body, Bytes, HttpBody as _};

Expand Down Expand Up @@ -57,11 +57,11 @@ ffi_fn! {
///
/// This does not consume the `hyper_body *`, so it may be used to again.
/// However, it MUST NOT be used or freed until the related task completes.
fn hyper_body_data(body: *mut hyper_body) -> *mut Task {
fn hyper_body_data(body: *mut hyper_body) -> *mut hyper_task {
// This doesn't take ownership of the Body, so don't allow destructor
let mut body = ManuallyDrop::new(unsafe { Box::from_raw(body) });

Box::into_raw(Task::boxed(async move {
Box::into_raw(hyper_task::boxed(async move {
body.0.data().await.map(|res| res.map(hyper_buf))
}))
}
Expand All @@ -78,15 +78,15 @@ ffi_fn! {
/// chunks as they are received, or `HYPER_ITER_BREAK` to cancel.
///
/// This will consume the `hyper_body *`, you shouldn't use it anymore or free it.
fn hyper_body_foreach(body: *mut hyper_body, func: hyper_body_foreach_callback, userdata: *mut c_void) -> *mut Task {
fn hyper_body_foreach(body: *mut hyper_body, func: hyper_body_foreach_callback, userdata: *mut c_void) -> *mut hyper_task {
if body.is_null() {
return ptr::null_mut();
}

let mut body = unsafe { Box::from_raw(body) };
let userdata = UserDataPointer(userdata);

Box::into_raw(Task::boxed(async move {
Box::into_raw(hyper_task::boxed(async move {
while let Some(item) = body.0.data().await {
let chunk = item?;
if HYPER_ITER_CONTINUE != func(userdata.0, &hyper_buf(chunk)) {
Expand Down
16 changes: 8 additions & 8 deletions src/ffi/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use crate::rt::Executor as _;

use super::error::hyper_code;
use super::http_types::{hyper_request, hyper_response};
use super::io::Io;
use super::task::{hyper_task_return_type, AsTaskType, Exec, Task, WeakExec};
use super::io::hyper_io;
use super::task::{hyper_executor, hyper_task, hyper_task_return_type, AsTaskType, WeakExec};

pub struct hyper_clientconn_options {
builder: conn::Builder,
Expand All @@ -30,7 +30,7 @@ ffi_fn! {
///
/// The returned `hyper_task *` must be polled with an executor until the
/// handshake completes, at which point the value can be taken.
fn hyper_clientconn_handshake(io: *mut Io, options: *mut hyper_clientconn_options) -> *mut Task {
fn hyper_clientconn_handshake(io: *mut hyper_io, options: *mut hyper_clientconn_options) -> *mut hyper_task {
if io.is_null() {
return std::ptr::null_mut();
}
Expand All @@ -41,7 +41,7 @@ ffi_fn! {
let options = unsafe { Box::from_raw(options) };
let io = unsafe { Box::from_raw(io) };

Box::into_raw(Task::boxed(async move {
Box::into_raw(hyper_task::boxed(async move {
options.builder.handshake::<_, crate::Body>(io)
.await
.map(|(tx, conn)| {
Expand All @@ -59,7 +59,7 @@ ffi_fn! {
///
/// Returns a task that needs to be polled until it is ready. When ready, the
/// task yields a `hyper_response *`.
fn hyper_clientconn_send(conn: *mut hyper_clientconn, req: *mut hyper_request) -> *mut Task {
fn hyper_clientconn_send(conn: *mut hyper_clientconn, req: *mut hyper_request) -> *mut hyper_task {
if conn.is_null() {
return std::ptr::null_mut();
}
Expand All @@ -78,7 +78,7 @@ ffi_fn! {
fut.await.map(hyper_response::wrap)
};

Box::into_raw(Task::boxed(fut))
Box::into_raw(hyper_task::boxed(fut))
}
}

Expand Down Expand Up @@ -118,11 +118,11 @@ ffi_fn! {
/// Set the client background task executor.
///
/// This does not consume the `options` or the `exec`.
fn hyper_clientconn_options_exec(opts: *mut hyper_clientconn_options, exec: *const Exec) {
fn hyper_clientconn_options_exec(opts: *mut hyper_clientconn_options, exec: *const hyper_executor) {
let opts = unsafe { &mut *opts };

let exec = unsafe { Arc::from_raw(exec) };
let weak_exec = Exec::downgrade(&exec);
let weak_exec = hyper_executor::downgrade(&exec);
std::mem::forget(exec);

opts.builder.executor(weak_exec.clone());
Expand Down
22 changes: 11 additions & 11 deletions src/ffi/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type hyper_io_read_callback =
type hyper_io_write_callback =
extern "C" fn(*mut c_void, *mut hyper_context<'_>, *const u8, size_t) -> size_t;

pub struct Io {
pub struct hyper_io {
read: hyper_io_read_callback,
write: hyper_io_write_callback,
userdata: *mut c_void,
Expand All @@ -26,8 +26,8 @@ ffi_fn! {
///
/// The read and write functions of this transport should be set with
/// `hyper_io_set_read` and `hyper_io_set_write`.
fn hyper_io_new() -> *mut Io {
Box::into_raw(Box::new(Io {
fn hyper_io_new() -> *mut hyper_io {
Box::into_raw(Box::new(hyper_io {
read: read_noop,
write: write_noop,
userdata: std::ptr::null_mut(),
Expand All @@ -40,7 +40,7 @@ ffi_fn! {
///
/// This is typically only useful if you aren't going to pass ownership
/// of the IO handle to hyper, such as with `hyper_clientconn_handshake()`.
fn hyper_io_free(io: *mut Io) {
fn hyper_io_free(io: *mut hyper_io) {
drop(unsafe { Box::from_raw(io) });
}
}
Expand All @@ -49,7 +49,7 @@ ffi_fn! {
/// Set the user data pointer for this IO to some value.
///
/// This value is passed as an argument to the read and write callbacks.
fn hyper_io_set_userdata(io: *mut Io, data: *mut c_void) {
fn hyper_io_set_userdata(io: *mut hyper_io, data: *mut c_void) {
unsafe { &mut *io }.userdata = data;
}
}
Expand All @@ -71,7 +71,7 @@ ffi_fn! {
///
/// If there is an irrecoverable error reading data, then `HYPER_IO_ERROR`
/// should be the return value.
fn hyper_io_set_read(io: *mut Io, func: hyper_io_read_callback) {
fn hyper_io_set_read(io: *mut hyper_io, func: hyper_io_read_callback) {
unsafe { &mut *io }.read = func;
}
}
Expand All @@ -90,7 +90,7 @@ ffi_fn! {
///
/// If there is an irrecoverable error reading data, then `HYPER_IO_ERROR`
/// should be the return value.
fn hyper_io_set_write(io: *mut Io, func: hyper_io_write_callback) {
fn hyper_io_set_write(io: *mut hyper_io, func: hyper_io_write_callback) {
unsafe { &mut *io }.write = func;
}
}
Expand All @@ -115,7 +115,7 @@ extern "C" fn write_noop(
0
}

impl AsyncRead for Io {
impl AsyncRead for hyper_io {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
Expand All @@ -141,7 +141,7 @@ impl AsyncRead for Io {
}
}

impl AsyncWrite for Io {
impl AsyncWrite for hyper_io {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
Expand Down Expand Up @@ -169,5 +169,5 @@ impl AsyncWrite for Io {
}
}

unsafe impl Send for Io {}
unsafe impl Sync for Io {}
unsafe impl Send for hyper_io {}
unsafe impl Sync for hyper_io {}
56 changes: 28 additions & 28 deletions src/ffi/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub const HYPER_POLL_READY: c_int = 0;
pub const HYPER_POLL_PENDING: c_int = 1;
pub const HYPER_POLL_ERROR: c_int = 3;

pub struct Exec {
pub struct hyper_executor {
/// The executor of all task futures.
///
/// There should never be contention on the mutex, as it is only locked
Expand All @@ -38,23 +38,23 @@ pub struct Exec {
spawn_queue: Mutex<Vec<TaskFuture>>,

/// This is used to track when a future calls `wake` while we are within
/// `Exec::poll_next`.
/// `hyper_executor::poll_next`.
is_woken: Arc<ExecWaker>,
}

#[derive(Clone)]
pub(crate) struct WeakExec(Weak<Exec>);
pub(crate) struct WeakExec(Weak<hyper_executor>);

struct ExecWaker(AtomicBool);

pub struct Task {
pub struct hyper_task {
future: BoxFuture<BoxAny>,
output: Option<BoxAny>,
userdata: UserDataPointer,
}

struct TaskFuture {
task: Option<Box<Task>>,
task: Option<Box<hyper_task>>,
}

pub struct hyper_context<'a>(Context<'a>);
Expand Down Expand Up @@ -85,29 +85,29 @@ pub(crate) trait IntoDynTaskType {
fn into_dyn_task_type(self) -> BoxAny;
}

// ===== impl Exec =====
// ===== impl hyper_executor =====

impl Exec {
fn new() -> Arc<Exec> {
Arc::new(Exec {
impl hyper_executor {
fn new() -> Arc<hyper_executor> {
Arc::new(hyper_executor {
driver: Mutex::new(FuturesUnordered::new()),
spawn_queue: Mutex::new(Vec::new()),
is_woken: Arc::new(ExecWaker(AtomicBool::new(false))),
})
}

pub(crate) fn downgrade(exec: &Arc<Exec>) -> WeakExec {
pub(crate) fn downgrade(exec: &Arc<hyper_executor>) -> WeakExec {
WeakExec(Arc::downgrade(exec))
}

fn spawn(&self, task: Box<Task>) {
fn spawn(&self, task: Box<hyper_task>) {
self.spawn_queue
.lock()
.unwrap()
.push(TaskFuture { task: Some(task) });
}

fn poll_next(&self) -> Option<Box<Task>> {
fn poll_next(&self) -> Option<Box<hyper_task>> {
// Drain the queue first.
self.drain_queue();

Expand Down Expand Up @@ -169,21 +169,21 @@ impl WeakExec {
impl crate::rt::Executor<BoxFuture<()>> for WeakExec {
fn execute(&self, fut: BoxFuture<()>) {
if let Some(exec) = self.0.upgrade() {
exec.spawn(Task::boxed(fut));
exec.spawn(hyper_task::boxed(fut));
}
}
}

ffi_fn! {
/// Creates a new task executor.
fn hyper_executor_new() -> *const Exec {
Arc::into_raw(Exec::new())
fn hyper_executor_new() -> *const hyper_executor {
Arc::into_raw(hyper_executor::new())
}
}

ffi_fn! {
/// Frees an executor and any incomplete tasks still part of it.
fn hyper_executor_free(exec: *const Exec) {
fn hyper_executor_free(exec: *const hyper_executor) {
drop(unsafe { Arc::from_raw(exec) });
}
}
Expand All @@ -193,7 +193,7 @@ ffi_fn! {
///
/// The executor takes ownership of the task, it should not be accessed
/// again unless returned back to the user with `hyper_executor_poll`.
fn hyper_executor_push(exec: *const Exec, task: *mut Task) -> hyper_code {
fn hyper_executor_push(exec: *const hyper_executor, task: *mut hyper_task) -> hyper_code {
if exec.is_null() || task.is_null() {
return hyper_code::HYPERE_INVALID_ARG;
}
Expand All @@ -211,7 +211,7 @@ ffi_fn! {
/// If ready, returns a task from the executor that has completed.
///
/// If there are no ready tasks, this returns `NULL`.
fn hyper_executor_poll(exec: *const Exec) -> *mut Task {
fn hyper_executor_poll(exec: *const hyper_executor) -> *mut hyper_task {
// We only want an `&Arc` in here, so wrap in a `ManuallyDrop` so we
// don't accidentally trigger a ref_dec of the Arc.
let exec = unsafe { &*exec };
Expand All @@ -222,15 +222,15 @@ ffi_fn! {
}
}

// ===== impl Task =====
// ===== impl hyper_task =====

impl Task {
pub(crate) fn boxed<F>(fut: F) -> Box<Task>
impl hyper_task {
pub(crate) fn boxed<F>(fut: F) -> Box<hyper_task>
where
F: Future + Send + 'static,
F::Output: IntoDynTaskType + Send + Sync + 'static,
{
Box::new(Task {
Box::new(hyper_task {
future: Box::pin(async move { fut.await.into_dyn_task_type() }),
output: None,
userdata: UserDataPointer(ptr::null_mut()),
Expand All @@ -246,7 +246,7 @@ impl Task {
}

impl Future for TaskFuture {
type Output = Box<Task>;
type Output = Box<hyper_task>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match Pin::new(&mut self.task.as_mut().unwrap().future).poll(cx) {
Expand All @@ -262,7 +262,7 @@ impl Future for TaskFuture {

ffi_fn! {
/// Free a task.
fn hyper_task_free(task: *mut Task) {
fn hyper_task_free(task: *mut hyper_task) {
drop(unsafe { Box::from_raw(task) });
}
}
Expand All @@ -274,7 +274,7 @@ ffi_fn! {
/// this task.
///
/// Use `hyper_task_type` to determine the type of the `void *` return value.
fn hyper_task_value(task: *mut Task) -> *mut c_void {
fn hyper_task_value(task: *mut hyper_task) -> *mut c_void {
if task.is_null() {
return ptr::null_mut();
}
Expand All @@ -297,7 +297,7 @@ ffi_fn! {

ffi_fn! {
/// Query the return type of this task.
fn hyper_task_type(task: *mut Task) -> hyper_task_return_type {
fn hyper_task_type(task: *mut hyper_task) -> hyper_task_return_type {
if task.is_null() {
// instead of blowing up spectacularly, just say this null task
// doesn't have a value to retrieve.
Expand All @@ -313,7 +313,7 @@ ffi_fn! {
///
/// This value will be passed to task callbacks, and can be checked later
/// with `hyper_task_userdata`.
fn hyper_task_set_userdata(task: *mut Task, userdata: *mut c_void) {
fn hyper_task_set_userdata(task: *mut hyper_task, userdata: *mut c_void) {
if task.is_null() {
return;
}
Expand All @@ -324,7 +324,7 @@ ffi_fn! {

ffi_fn! {
/// Retrieve the userdata that has been set via `hyper_task_set_userdata`.
fn hyper_task_userdata(task: *mut Task) -> *mut c_void {
fn hyper_task_userdata(task: *mut hyper_task) -> *mut c_void {
if task.is_null() {
return ptr::null_mut();
}
Expand Down

0 comments on commit a602808

Please sign in to comment.