~jojo/Carth

ref: c5a394b01aa60cb95605d66f6118cfb231955aa7 Carth/std-rs/src/io.rs -rw-r--r-- 1.3 KiB
c5a394b0JoJo Fix class constraint inference bug when explicit scheme given a year ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use std::io::{self, Read, Write};
use std::mem;

use crate::*;

pub trait ReadWrite: Read + Write {}

impl<T> ReadWrite for T where T: Read + Write {}

pub type Handle = *mut dyn ReadWrite;

#[derive(Clone, Copy)]
#[repr(C)]
pub struct FfiHandle(*mut u8, *mut u8);

pub fn handle_to_ffi(h: Handle) -> FfiHandle {
    unsafe { mem::transmute(h) }
}

pub unsafe fn handle_from_ffi(h: FfiHandle) -> Handle {
    mem::transmute(h)
}

#[no_mangle]
pub unsafe extern "C" fn stdrs_close_handle(h: FfiHandle) {
    drop(Box::from_raw(handle_from_ffi(h)))
}

#[no_mangle]
pub unsafe extern "C" fn stdrs_read_handle(
    h: FfiHandle,
    mut buf: Array<u8>,
) -> Cons<Array<u8>, Maybe<usize>> {
    let res = (*handle_from_ffi(h)).read(buf.as_slice_mut());
    Cons(
        buf,
        match res {
            Ok(n) => Maybe::Some(n),
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => Maybe::Some(0),
            Err(_) => Maybe::None,
        },
    )
}

#[no_mangle]
pub unsafe extern "C" fn stdrs_write_handle(
    h: FfiHandle,
    buf: Array<u8>,
) -> Cons<Array<u8>, Maybe<usize>> {
    let res = (*handle_from_ffi(h)).write(buf.as_slice());
    Cons(
        buf,
        match res {
            Ok(n) => Maybe::Some(n),
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => Maybe::Some(0),
            Err(_) => Maybe::None,
        },
    )
}