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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#[cfg(not(windows))]
mod module {
extern crate libc;
use self::libc::{c_void, free};
use std::ffi::{CString, CStr};
mod sys {
use super::libc::{c_char};
#[link(name = "readline")]
extern {
pub fn readline(prompt: *const c_char) -> *mut c_char;
pub fn add_history(line: *const c_char);
}
}
pub fn readline(prompt: &str) -> Option<String> {
let c_prompt = CString::new(prompt.to_string()).ok()
.expect("The given prompt contains NUL bytes");
let result_ptr = unsafe { sys::readline(c_prompt.as_ptr()) };
if result_ptr.is_null() {
return None
}
let result_c_str = unsafe { CStr::from_ptr(result_ptr) };
let result = String::from_utf8_lossy(result_c_str.to_bytes()).into_owned();
unsafe {
free(result_c_str.as_ptr() as *mut c_void);
};
Some(result)
}
pub fn add_history(line: &str) {
let c_line = CString::new(line.as_bytes()).ok()
.expect("The given line contains NUL bytes");
unsafe {
sys::add_history(c_line.as_ptr());
}
}
}
#[cfg(windows)]
mod module {
use std::io::{self, Write};
pub fn readline(prompt: &str) -> Option<String> {
print!("{}", prompt);
io::stdout().flush().unwrap();
let mut stdin = io::stdin();
let mut line = String::new();
match stdin.read_line(&mut line) {
Ok(0) => None,
Ok(_) => Some(line),
Err(e) => panic!("Error in readline: {}", e),
}
}
pub fn add_history(_: &str) {}
}
pub use self::module::*;