~jojo/Carth

f0c55fb0c17b813f2f932772c3695b4a0c4f8859 — JoJo 1 year, 1 month ago 3656b8b
std: Add read-file
2 files changed, 40 insertions(+), 4 deletions(-)

M foreign-core/src/lib.rs
M std/io.carth
M foreign-core/src/lib.rs => foreign-core/src/lib.rs +37 -3
@@ 1,8 1,10 @@
#![feature(try_trait)]
#![allow(non_camel_case_types)]

mod ffi;

use libc::*;
use std::fs::File;
use std::io::{self, Read, Write};
use std::{alloc, mem, slice, str};



@@ 61,9 63,32 @@ impl Str {
}

#[repr(C)]
pub struct Pair<A, B> {
    fst: A,
    snd: B,
pub enum Maybe<A> {
    None,
    Some(A),
}

impl<A> std::ops::Try for Maybe<A> {
    type Ok = A;
    type Error = std::option::NoneError;

    #[inline]
    fn into_result(self) -> Result<A, std::option::NoneError> {
        match self {
            Maybe::None => Err(std::option::NoneError),
            Maybe::Some(x) => Ok(x),
        }
    }

    #[inline]
    fn from_ok(v: A) -> Self {
        Maybe::Some(v)
    }

    #[inline]
    fn from_error(_: std::option::NoneError) -> Self {
        Maybe::None
    }
}

// TODO: Do it properly.


@@ 131,6 156,15 @@ pub extern "C" fn get_contents() -> Str {
    Str::new(&s)
}

#[export_name = "unsafe-read-file"]
pub extern "C" fn read_file(fp: Str) -> Maybe<Str> {
    let fp = from_carth_str(&fp);
    let mut f = File::open(fp).ok()?;
    let mut s = String::new();
    f.read_to_string(&mut s).ok()?;
    Maybe::Some(Str::new(&s))
}

// NOTE: This is a hack to ensure that Rust links in libm.
//
//       It seems that if no non-dead code makes use of functions from libm, then rustc or

M std/io.carth => std/io.carth +3 -1
@@ 39,5 39,7 @@
  (display-inline (str-append s "\n")))

(extern -get-contents (Fun RealWorld [Str RealWorld]))

(define get-contents (IO -get-contents))

(extern unsafe-read-file (Fun Str (Maybe Str)))
(define (read-file f) (IO (fun (real-world) [(unsafe-read-file f) real-world])))