forked from dobkeratops/rustfind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ioutil.rs
248 lines (207 loc) · 6.55 KB
/
ioutil.rs
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#![macro_escape]
use std::io::{File, UserDir};
use std::io::fs::{mkdir_recursive,copy,walk_dir};
use std::cast;
pub use std::io::{stdout, stdin};
pub use libc::{fwrite, fread, fseek, fopen, ftell, fclose, FILE, c_void, c_char, SEEK_END,
SEEK_SET};
pub use std::mem::size_of; // for size_of
pub use std::num::Zero;
use std::io::{BufferedReader, IoResult};
use std::vec::Vec;
use std::vec;
pub type Size_t=u64; // todo - we're not sure this should be u64
// as the libc stuff seems to want.
// should it be uint?
// TODO cleanup, we can just use the mature rust fileio now.
macro_rules! logi{
($($a:expr),*)=>(println!("{}", file!()+":"+line!().to_str()+": " $(+$a.to_str())* ))
}
//macro_rules! dump{ ($a:expr)=>(logi!(fmt!("%s=%?",stringify!($a),$a).indent(2,160));)}
/*fn newline_if_over(a:StrBuf,l:uint) -> StrBuf {
if a.len()>l {
a+"\n"
} else {
a
}
}*/
macro_rules! dump{ ($($a:expr),*)=>
( { let mut txt=StrBuf::new();
$( txt=txt.append(
format!("{:s}={:?}",stringify!($a),$a) + ",")
);*;
logi!(txt);
}
)
}
macro_rules! trace{
()=>(
println!("{}", file!().to_str()+":"+line!().to_str()+": ");
);
}
pub trait Dbprint {fn dbprint(&self);}
pub trait EndianSwap {
fn endian_swap(&self)->Self;
}
// dbprint postfix form means we can print tuples?
impl<T:ToStr> Dbprint for T {
fn dbprint(&self) {
println!("{}", self.to_str());
}
}
pub fn promptInput(prompt:&str)->StrBuf {
println!("{}", prompt);
StrBuf::from_str(BufferedReader::new(stdin()).read_line().unwrap()) // TODO add error handling
}
pub fn as_void_ptr<T>(a:&T)->*c_void { unsafe {cast::transmute(a) } }
pub fn as_mut_void_ptr<T>(a:&T)->*mut c_void {unsafe { cast::transmute(a) } }
// this doest work?
pub trait VoidPtr {
fn as_void_ptr(&self)->*c_void;
fn as_mut_void_ptr(&self)->*mut c_void;
}
impl<T> VoidPtr for T {
fn as_void_ptr(&self)->*c_void {unsafe { cast::transmute(self) } }
fn as_mut_void_ptr(&self)->*mut c_void {unsafe { cast::transmute(self) } }
}
pub fn printStr<T:ToStr>(a:&T){println!("{}", a.to_str());}
pub fn c_str(rustStr:&str)->*c_char {
unsafe {
// as_c_str(rustStr,|x|x)
rustStr.to_c_str().unwrap()
}
}
pub unsafe fn fileOpen(filename:&str,mode:&str)-> *FILE {
fopen(c_str(filename),c_str(mode))
}
pub fn file_create_with_dirs(file_path: &Path) -> IoResult<File> {
use std::io::{File, UserDir};
use std::io::fs::mkdir_recursive;
mkdir_recursive(&file_path.dir_path(), UserDir).and_then(|()| {
File::create(file_path)
}).map_err(|e| {
println!("error: could not write to {} - {}", file_path.display(), e);
e
})
}
/*
pub fn fileLoadArray<T>(filename:&str)->~[T] {
unsafe {
let fp=fopen(c_str_from(filename),as_c_str("rb",|x|x));
}
}
*/
pub unsafe fn fileWrite<T>(fp:*FILE, array:&[T]) {
printStr(&sizeofArray(array));
fwrite(as_void_ptr(&array[0]),sizeofArray(array),1,fp);
}
pub unsafe fn fileWriteStruct<T>(fp:*FILE, s:&T) {
fwrite(as_void_ptr(s),size_of::<T>() as Size_t,1,fp);
}
pub unsafe fn fileRead<T:Zero+Clone>(fp:*FILE,numElems:Size_t)->Vec<T> {
let buffer=Vec::from_elem(numElems as uint, Zero::zero());
fread(as_mut_void_ptr(&buffer.get(0)),numElems,size_of::<T>() as Size_t,fp);
buffer
}
pub unsafe fn fileReadBytes(fp:*FILE,numBytes:Size_t)->Vec<u8> {
// todo - simply express as the above..
let buffer=Vec::from_elem(numBytes as uint,0 as u8);
fread(as_mut_void_ptr(buffer.get(0)),numBytes,1,fp);
buffer
}
pub unsafe fn fileSize(fp:*FILE)->Size_t {
fseek(fp,0,SEEK_END);
let pos=ftell(fp);
fseek(fp,0,SEEK_SET);
pos as Size_t
}
pub fn fileLoad(filename:&str)->Vec<u8> {
unsafe {
// TODO - should do with patter match null, fp?
let fp= fileOpen(filename,"rb");
if fp==0 as *FILE {
printStr(&("could not read "+filename));
Vec::new()
}
else
{
let buffer=fileReadBytes(fp,fileSize(fp));
fclose(fp);
buffer
}
}
}
pub unsafe fn fileWriteRange<T>(fp:*FILE, array:&[T],start:uint,end:uint) {
printStr(&sizeofArray(array));
fwrite(as_void_ptr(&array[start]),sizeofArrayElem(array)*(end-start) as Size_t,1,fp);
}
pub fn sizeofArray<T>(a:&[T])->Size_t { (size_of::<T>() * a.len()) as Size_t }
pub fn sizeofArrayElem<T>(_:&[T])->Size_t { size_of::<T>() as Size_t }
pub fn fileSaveArray<T>(buffer:&[T],filename:&str) {
unsafe {
let fp=fileOpen(filename,"wb");
if fp!=(0 as *FILE) {
fileWrite(fp,buffer);
//fwrite(to_void_ptr(&buffer[0]),sizeofArray(buffer),1,fp);
fclose(fp);
} else {
printStr(&("could not write "+filename));
}
}
}
pub fn fileSaveStr(text:&str, file_path: &Path) {
let res = mkdir_recursive(&file_path.dir_path(), UserDir).and_then(|()| {
let mut file = File::create(file_path);
file.write_str(text)
});
match res {
Ok(()) => (),
Err(e) => println!("error: could not write to {} - {}", file_path.display(), e)
};
}
pub fn copy_folder(source_dir: &Path, dest_dir: &Path)->Result<(),()> {
let directories = walk_dir(source_dir);
let res = match directories {
Ok(mut directories) => {
let mut result = Ok(());
for file in directories {
let mut dest_path = Path::new(dest_dir);
for c in file.components().skip(1) {
dest_path.push(c);
}
let res = if file.is_dir () {
mkdir_recursive(&dest_path, UserDir)
} else {
copy(&file, &dest_path)
};
match res {
Err(e) => {
result = Err(e);
break;
},
_ => ()
}
};
result
},
Err(e) => {
println!("Unable to copy directory `{}`: {}", source_dir.display(), e);
return Err(());
}
};
match res {
Err(e) => {println!("Error while copying: {}", e)return Err(()) },
_ => return Ok(())
}
}
pub trait ResultUtil<T> {
fn expect(self, error_message: &'static str) -> T;
}
impl<T, U> ResultUtil<T> for Result<T, U> {
fn expect(self, error_message: &'static str) -> T {
match self {
Ok(res) => res,
Err(_) => fail!(error_message)
}
}
}