Reputation: 7825
I'm starting to use rust to create a little toy command prompt applicationusing the gnu readline library. I started using the c foreign function interface but then came across this in rust 0.8.
The crate extra has a module extra::rl
which appears to be a readline with all the tools that are needed. My question is, is this present in rust 0.10 and if so where is it? if not, is it packaged as an external module, and if so where can I find it?
Thanks in advance.
Upvotes: 2
Views: 397
Reputation: 3886
use std::c_str;
#[link(name = "readline")]
extern {
fn readline (p: *std::libc::c_char) -> * std::libc::c_char;
}
fn rust_readline (prompt: &str) -> Option<~str> {
let cprmt = prompt.to_c_str();
cprmt.with_ref(|c_buf| {
unsafe {
let ret = c_str::CString::new (readline (c_buf), true);
ret.as_str().map(|ret| ret.to_owned())
}
})
}
fn eval(input: &str)
{
println! ("{}", input);
}
fn main()
{
loop {
let val = rust_readline (">>> ");
match val {
None => { break }
_ => {
let input = val.unwrap ();
eval(input);
}
}
}
}
This is a sample REPL style interpreter that just prints instead of eval'ing. Based on code from http://redbrain.co.uk/2013/11/09/rust-and-readline-c-ffi/. His example no longer compiles.
This code is now on github here.
Upvotes: 1
Reputation: 7825
Sorry I really should have said, I came up with an answer to my own question, it includes a history for readline. I have put it here in case anyone else wants some of this functionality.
//! Readline FFI
//extern crate libc;
use std::libc;
use libc::c_char;
use std::c_str;
#[link(name = "readline")]
extern {
fn readline(p: *c_char) -> * c_char;
fn add_history(l: *c_char);
}
pub fn rust_readline(prompt: &str) -> Option<~str> {
let c_prompt = prompt.to_c_str();
c_prompt.with_ref(|c_buf| {
unsafe {
let ret = c_str::CString::new(readline(c_buf), true);
ret.as_str().map(|ret| ret.to_owned())
}
})
}
pub fn rust_add_history(line: &str) -> int {
// if line.len() == 0 { return Err("Empty string!") }
let c_line = line.to_c_str();
c_line.with_ref(|my_c_line| {
unsafe {
// println!("{}", my_c_line)
add_history(my_c_line);
}
});
0
}
fn main() {
loop {
let val = rust_readline("mikes_lisp> ");
match val {
None => { break }
_ => {
let input = val.unwrap();
rust_add_history(input);
println!("you said: '{}'", input);
}
}
}
}
Upvotes: 1