forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio.rs
More file actions
1432 lines (1214 loc) · 39.3 KB
/
io.rs
File metadata and controls
1432 lines (1214 loc) · 39.3 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Basic input/output
*/
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
use result::Result;
use cmp::Eq;
use dvec::DVec;
use int;
use libc;
use libc::{c_int, c_long, c_uint, c_void, size_t, ssize_t};
use libc::consts::os::posix88::*;
use libc::consts::os::extra::*;
use option;
use os;
use prelude::*;
use ptr;
use result;
use str;
use uint;
use vec;
#[allow(non_camel_case_types)] // not sure what to do about this
pub type fd_t = c_int;
#[abi = "cdecl"]
extern mod rustrt {
unsafe fn rust_get_stdin() -> *libc::FILE;
unsafe fn rust_get_stdout() -> *libc::FILE;
unsafe fn rust_get_stderr() -> *libc::FILE;
}
// Reading
// FIXME (#2004): This is all buffered. We might need an unbuffered variant
// as well
pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, }
/// The raw underlying reader trait. All readers must implement this.
pub trait Reader {
// FIXME (#2004): Seekable really should be orthogonal.
/// Read up to len bytes (or EOF) and put them into bytes (which
/// must be at least len bytes long). Return number of bytes read.
// FIXME (#2982): This should probably return an error.
fn read(&self, bytes: &[mut u8], len: uint) -> uint;
/// Read a single byte, returning a negative value for EOF or read error.
fn read_byte(&self) -> int;
/// Return whether the stream is currently at EOF position.
fn eof(&self) -> bool;
/// Move the current position within the stream. The second parameter
/// determines the position that the first parameter is relative to.
fn seek(&self, position: int, style: SeekStyle);
/// Return the current position within the stream.
fn tell(&self) -> uint;
}
/// Generic utility functions defined on readers.
pub trait ReaderUtil {
/// Read len bytes into a new vec.
fn read_bytes(&self, len: uint) -> ~[u8];
/// Read up until the first '\n' char (which is not returned), or EOF.
fn read_line(&self) -> ~str;
/// Read n utf-8 encoded chars.
fn read_chars(&self, n: uint) -> ~[char];
/// Read a single utf-8 encoded char.
fn read_char(&self) -> char;
/// Read up until the first null byte (which is not returned), or EOF.
fn read_c_str(&self) -> ~str;
/// Read all the data remaining in the stream in one go.
fn read_whole_stream(&self) -> ~[u8];
/// Iterate over every byte until the iterator breaks or EOF.
fn each_byte(&self, it: fn(int) -> bool);
/// Iterate over every char until the iterator breaks or EOF.
fn each_char(&self, it: fn(char) -> bool);
/// Iterate over every line until the iterator breaks or EOF.
fn each_line(&self, it: fn(&str) -> bool);
/// Read n (between 1 and 8) little-endian unsigned integer bytes.
fn read_le_uint_n(&self, nbytes: uint) -> u64;
/// Read n (between 1 and 8) little-endian signed integer bytes.
fn read_le_int_n(&self, nbytes: uint) -> i64;
/// Read n (between 1 and 8) big-endian unsigned integer bytes.
fn read_be_uint_n(&self, nbytes: uint) -> u64;
/// Read n (between 1 and 8) big-endian signed integer bytes.
fn read_be_int_n(&self, nbytes: uint) -> i64;
/// Read a little-endian uint (number of bytes depends on system).
fn read_le_uint(&self) -> uint;
/// Read a little-endian int (number of bytes depends on system).
fn read_le_int(&self) -> int;
/// Read a big-endian uint (number of bytes depends on system).
fn read_be_uint(&self) -> uint;
/// Read a big-endian int (number of bytes depends on system).
fn read_be_int(&self) -> int;
/// Read a big-endian u64 (8 bytes).
fn read_be_u64(&self) -> u64;
/// Read a big-endian u32 (4 bytes).
fn read_be_u32(&self) -> u32;
/// Read a big-endian u16 (2 bytes).
fn read_be_u16(&self) -> u16;
/// Read a big-endian i64 (8 bytes).
fn read_be_i64(&self) -> i64;
/// Read a big-endian i32 (4 bytes).
fn read_be_i32(&self) -> i32;
/// Read a big-endian i16 (2 bytes).
fn read_be_i16(&self) -> i16;
/// Read a little-endian u64 (8 bytes).
fn read_le_u64(&self) -> u64;
/// Read a little-endian u32 (4 bytes).
fn read_le_u32(&self) -> u32;
/// Read a little-endian u16 (2 bytes).
fn read_le_u16(&self) -> u16;
/// Read a litle-endian i64 (8 bytes).
fn read_le_i64(&self) -> i64;
/// Read a litle-endian i32 (4 bytes).
fn read_le_i32(&self) -> i32;
/// Read a litle-endian i16 (2 bytes).
fn read_le_i16(&self) -> i16;
/// Read a u8 (1 byte).
fn read_u8(&self) -> u8;
/// Read a i8 (1 byte).
fn read_i8(&self) -> i8;
}
impl<T: Reader> T : ReaderUtil {
fn read_bytes(&self,len: uint) -> ~[u8] {
let mut bytes = vec::with_capacity(len);
unsafe { vec::raw::set_len(&mut bytes, len); }
let count = self.read(bytes, len);
unsafe { vec::raw::set_len(&mut bytes, count); }
move bytes
}
fn read_line(&self) -> ~str {
let mut bytes = ~[];
loop {
let ch = self.read_byte();
if ch == -1 || ch == 10 { break; }
bytes.push(ch as u8);
}
str::from_bytes(bytes)
}
fn read_chars(&self, n: uint) -> ~[char] {
// returns the (consumed offset, n_req), appends characters to &chars
fn chars_from_bytes<T: Reader>(bytes: &~[u8], chars: &mut ~[char])
-> (uint, uint) {
let mut i = 0;
let bytes_len = bytes.len();
while i < bytes_len {
let b0 = bytes[i];
let w = str::utf8_char_width(b0);
let end = i + w;
i += 1;
assert (w > 0);
if w == 1 {
chars.push(b0 as char);
loop;
}
// can't satisfy this char with the existing data
if end > bytes_len {
return (i - 1, end - bytes_len);
}
let mut val = 0;
while i < end {
let next = bytes[i] as int;
i += 1;
assert (next > -1);
assert (next & 192 == 128);
val <<= 6;
val += (next & 63) as uint;
}
// See str::char_at
val += ((b0 << ((w + 1) as u8)) as uint)
<< (w - 1) * 6 - w - 1u;
chars.push(val as char);
}
return (i, 0);
}
let mut bytes = ~[];
let mut chars = ~[];
// might need more bytes, but reading n will never over-read
let mut nbread = n;
while nbread > 0 {
let data = self.read_bytes(nbread);
if data.is_empty() {
// eof - FIXME (#2004): should we do something if
// we're split in a unicode char?
break;
}
bytes.push_all(data);
let (offset, nbreq) = chars_from_bytes::<T>(&bytes, &mut chars);
let ncreq = n - chars.len();
// again we either know we need a certain number of bytes
// to complete a character, or we make sure we don't
// over-read by reading 1-byte per char needed
nbread = if ncreq > nbreq { ncreq } else { nbreq };
if nbread > 0 {
bytes = vec::slice(bytes, offset, bytes.len());
}
}
move chars
}
fn read_char(&self) -> char {
let c = self.read_chars(1);
if vec::len(c) == 0 {
return -1 as char; // FIXME will this stay valid? // #2004
}
assert(vec::len(c) == 1);
return c[0];
}
fn read_c_str(&self) -> ~str {
let mut bytes: ~[u8] = ~[];
loop {
let ch = self.read_byte();
if ch < 1 { break; } else { bytes.push(ch as u8); }
}
str::from_bytes(bytes)
}
fn read_whole_stream(&self) -> ~[u8] {
let mut bytes: ~[u8] = ~[];
while !self.eof() { bytes.push_all(self.read_bytes(2048u)); }
move bytes
}
fn each_byte(&self, it: fn(int) -> bool) {
while !self.eof() {
if !it(self.read_byte()) { break; }
}
}
fn each_char(&self, it: fn(char) -> bool) {
while !self.eof() {
if !it(self.read_char()) { break; }
}
}
fn each_line(&self, it: fn(s: &str) -> bool) {
while !self.eof() {
if !it(self.read_line()) { break; }
}
}
// FIXME int reading methods need to deal with eof - issue #2004
fn read_le_uint_n(&self, nbytes: uint) -> u64 {
assert nbytes > 0 && nbytes <= 8;
let mut val = 0u64, pos = 0, i = nbytes;
while i > 0 {
val += (self.read_u8() as u64) << pos;
pos += 8;
i -= 1;
}
val
}
fn read_le_int_n(&self, nbytes: uint) -> i64 {
extend_sign(self.read_le_uint_n(nbytes), nbytes)
}
fn read_be_uint_n(&self, nbytes: uint) -> u64 {
assert nbytes > 0 && nbytes <= 8;
let mut val = 0u64, i = nbytes;
while i > 0 {
i -= 1;
val += (self.read_u8() as u64) << i * 8;
}
val
}
fn read_be_int_n(&self, nbytes: uint) -> i64 {
extend_sign(self.read_be_uint_n(nbytes), nbytes)
}
fn read_le_uint(&self) -> uint {
self.read_le_uint_n(uint::bytes) as uint
}
fn read_le_int(&self) -> int {
self.read_le_int_n(int::bytes) as int
}
fn read_be_uint(&self) -> uint {
self.read_be_uint_n(uint::bytes) as uint
}
fn read_be_int(&self) -> int {
self.read_be_int_n(int::bytes) as int
}
fn read_be_u64(&self) -> u64 {
self.read_be_uint_n(8) as u64
}
fn read_be_u32(&self) -> u32 {
self.read_be_uint_n(4) as u32
}
fn read_be_u16(&self) -> u16 {
self.read_be_uint_n(2) as u16
}
fn read_be_i64(&self) -> i64 {
self.read_be_int_n(8) as i64
}
fn read_be_i32(&self) -> i32 {
self.read_be_int_n(4) as i32
}
fn read_be_i16(&self) -> i16 {
self.read_be_int_n(2) as i16
}
fn read_le_u64(&self) -> u64 {
self.read_le_uint_n(8) as u64
}
fn read_le_u32(&self) -> u32 {
self.read_le_uint_n(4) as u32
}
fn read_le_u16(&self) -> u16 {
self.read_le_uint_n(2) as u16
}
fn read_le_i64(&self) -> i64 {
self.read_le_int_n(8) as i64
}
fn read_le_i32(&self) -> i32 {
self.read_le_int_n(4) as i32
}
fn read_le_i16(&self) -> i16 {
self.read_le_int_n(2) as i16
}
fn read_u8(&self) -> u8 {
self.read_byte() as u8
}
fn read_i8(&self) -> i8 {
self.read_byte() as i8
}
}
fn extend_sign(val: u64, nbytes: uint) -> i64 {
let shift = (8 - nbytes) * 8;
(val << shift) as i64 >> shift
}
// Reader implementations
fn convert_whence(whence: SeekStyle) -> i32 {
return match whence {
SeekSet => 0i32,
SeekCur => 1i32,
SeekEnd => 2i32
};
}
impl *libc::FILE: Reader {
fn read(&self, bytes: &[mut u8], len: uint) -> uint {
unsafe {
do vec::as_mut_buf(bytes) |buf_p, buf_len| {
assert buf_len >= len;
let count = libc::fread(buf_p as *mut c_void, 1u as size_t,
len as size_t, *self);
count as uint
}
}
}
fn read_byte(&self) -> int {
unsafe {
libc::fgetc(*self) as int
}
}
fn eof(&self) -> bool {
unsafe {
return libc::feof(*self) != 0 as c_int;
}
}
fn seek(&self, offset: int, whence: SeekStyle) {
unsafe {
assert libc::fseek(*self,
offset as c_long,
convert_whence(whence)) == 0 as c_int;
}
}
fn tell(&self) -> uint {
unsafe {
return libc::ftell(*self) as uint;
}
}
}
struct Wrapper<T, C> {
base: T,
cleanup: C,
}
// A forwarding impl of reader that also holds on to a resource for the
// duration of its lifetime.
// FIXME there really should be a better way to do this // #2004
impl<R: Reader, C> Wrapper<R, C>: Reader {
fn read(&self, bytes: &[mut u8], len: uint) -> uint {
self.base.read(bytes, len)
}
fn read_byte(&self) -> int { self.base.read_byte() }
fn eof(&self) -> bool { self.base.eof() }
fn seek(&self, off: int, whence: SeekStyle) {
self.base.seek(off, whence)
}
fn tell(&self) -> uint { self.base.tell() }
}
pub struct FILERes {
f: *libc::FILE,
drop {
unsafe {
libc::fclose(self.f);
}
}
}
pub fn FILERes(f: *libc::FILE) -> FILERes {
FILERes {
f: f
}
}
pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> Reader {
if cleanup {
Wrapper { base: f, cleanup: FILERes(f) } as Reader
} else {
f as Reader
}
}
// FIXME (#2004): this should either be an trait-less impl, a set of
// top-level functions that take a reader, or a set of default methods on
// reader (which can then be called reader)
pub fn stdin() -> Reader {
unsafe {
rustrt::rust_get_stdin() as Reader
}
}
pub fn file_reader(path: &Path) -> Result<Reader, ~str> {
unsafe {
let f = os::as_c_charp(path.to_str(), |pathbuf| {
os::as_c_charp("r", |modebuf|
libc::fopen(pathbuf, modebuf)
)
});
return if f as uint == 0u { result::Err(~"error opening "
+ path.to_str()) }
else {
result::Ok(FILE_reader(f, true))
}
}
}
// Byte readers
pub struct BytesReader {
bytes: &[u8],
mut pos: uint
}
impl BytesReader: Reader {
fn read(&self, bytes: &[mut u8], len: uint) -> uint {
let count = uint::min(len, self.bytes.len() - self.pos);
let view = vec::view(self.bytes, self.pos, self.bytes.len());
vec::bytes::copy_memory(bytes, view, count);
self.pos += count;
count
}
fn read_byte(&self) -> int {
if self.pos == self.bytes.len() { return -1; }
let b = self.bytes[self.pos];
self.pos += 1u;
return b as int;
}
fn eof(&self) -> bool { self.pos == self.bytes.len() }
fn seek(&self, offset: int, whence: SeekStyle) {
let pos = self.pos;
self.pos = seek_in_buf(offset, pos, self.bytes.len(), whence);
}
fn tell(&self) -> uint { self.pos }
}
pub pure fn with_bytes_reader<t>(bytes: &[u8], f: fn(Reader) -> t) -> t {
f(BytesReader { bytes: bytes, pos: 0u } as Reader)
}
pub pure fn with_str_reader<T>(s: &str, f: fn(Reader) -> T) -> T {
str::byte_slice(s, |bytes| with_bytes_reader(bytes, f))
}
// Writing
pub enum FileFlag { Append, Create, Truncate, NoFlag, }
// What type of writer are we?
#[deriving_eq]
pub enum WriterType { Screen, File }
// FIXME (#2004): Seekable really should be orthogonal.
// FIXME (#2004): eventually u64
/// The raw underlying writer trait. All writers must implement this.
pub trait Writer {
/// Write all of the given bytes.
fn write(&self, v: &[const u8]);
/// Move the current position within the stream. The second parameter
/// determines the position that the first parameter is relative to.
fn seek(&self, int, SeekStyle);
/// Return the current position within the stream.
fn tell(&self) -> uint;
/// Flush the output buffer for this stream (if there is one).
fn flush(&self) -> int;
/// Determine if this Writer is writing to a file or not.
fn get_type(&self) -> WriterType;
}
impl<W: Writer, C> Wrapper<W, C>: Writer {
fn write(&self, bs: &[const u8]) { self.base.write(bs); }
fn seek(&self, off: int, style: SeekStyle) { self.base.seek(off, style); }
fn tell(&self) -> uint { self.base.tell() }
fn flush(&self) -> int { self.base.flush() }
fn get_type(&self) -> WriterType { File }
}
impl *libc::FILE: Writer {
fn write(&self, v: &[const u8]) {
unsafe {
do vec::as_const_buf(v) |vbuf, len| {
let nout = libc::fwrite(vbuf as *c_void,
1,
len as size_t,
*self);
if nout != len as size_t {
error!("error writing buffer");
log(error, os::last_os_error());
die!();
}
}
}
}
fn seek(&self, offset: int, whence: SeekStyle) {
unsafe {
assert libc::fseek(*self,
offset as c_long,
convert_whence(whence)) == 0 as c_int;
}
}
fn tell(&self) -> uint {
unsafe {
libc::ftell(*self) as uint
}
}
fn flush(&self) -> int {
unsafe {
libc::fflush(*self) as int
}
}
fn get_type(&self) -> WriterType {
unsafe {
let fd = libc::fileno(*self);
if libc::isatty(fd) == 0 { File }
else { Screen }
}
}
}
pub fn FILE_writer(f: *libc::FILE, cleanup: bool) -> Writer {
if cleanup {
Wrapper { base: f, cleanup: FILERes(f) } as Writer
} else {
f as Writer
}
}
impl fd_t: Writer {
fn write(&self, v: &[const u8]) {
unsafe {
let mut count = 0u;
do vec::as_const_buf(v) |vbuf, len| {
while count < len {
let vb = ptr::const_offset(vbuf, count) as *c_void;
let nout = libc::write(*self, vb, len as size_t);
if nout < 0 as ssize_t {
error!("error writing buffer");
log(error, os::last_os_error());
die!();
}
count += nout as uint;
}
}
}
}
fn seek(&self, _offset: int, _whence: SeekStyle) {
error!("need 64-bit foreign calls for seek, sorry");
die!();
}
fn tell(&self) -> uint {
error!("need 64-bit foreign calls for tell, sorry");
die!();
}
fn flush(&self) -> int { 0 }
fn get_type(&self) -> WriterType {
unsafe {
if libc::isatty(*self) == 0 { File } else { Screen }
}
}
}
pub struct FdRes {
fd: fd_t,
drop {
unsafe {
libc::close(self.fd);
}
}
}
pub fn FdRes(fd: fd_t) -> FdRes {
FdRes {
fd: fd
}
}
pub fn fd_writer(fd: fd_t, cleanup: bool) -> Writer {
if cleanup {
Wrapper { base: fd, cleanup: FdRes(fd) } as Writer
} else {
fd as Writer
}
}
pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
-> Result<Writer, ~str> {
#[cfg(windows)]
fn wb() -> c_int { (O_WRONLY | O_BINARY) as c_int }
#[cfg(unix)]
fn wb() -> c_int { O_WRONLY as c_int }
let mut fflags: c_int = wb();
for vec::each(flags) |f| {
match *f {
Append => fflags |= O_APPEND as c_int,
Create => fflags |= O_CREAT as c_int,
Truncate => fflags |= O_TRUNC as c_int,
NoFlag => ()
}
}
let fd = unsafe {
do os::as_c_charp(path.to_str()) |pathbuf| {
libc::open(pathbuf, fflags,
(S_IRUSR | S_IWUSR) as c_int)
}
};
if fd < (0 as c_int) {
result::Err(fmt!("error opening %s: %s", path.to_str(),
os::last_os_error()))
} else {
result::Ok(fd_writer(fd, true))
}
}
pub fn u64_to_le_bytes<T>(n: u64, size: uint,
f: fn(v: &[u8]) -> T) -> T {
assert size <= 8u;
match size {
1u => f(&[n as u8]),
2u => f(&[n as u8,
(n >> 8) as u8]),
4u => f(&[n as u8,
(n >> 8) as u8,
(n >> 16) as u8,
(n >> 24) as u8]),
8u => f(&[n as u8,
(n >> 8) as u8,
(n >> 16) as u8,
(n >> 24) as u8,
(n >> 32) as u8,
(n >> 40) as u8,
(n >> 48) as u8,
(n >> 56) as u8]),
_ => {
let mut bytes: ~[u8] = ~[], i = size, n = n;
while i > 0u {
bytes.push((n & 255_u64) as u8);
n >>= 8_u64;
i -= 1u;
}
f(bytes)
}
}
}
pub fn u64_to_be_bytes<T>(n: u64, size: uint,
f: fn(v: &[u8]) -> T) -> T {
assert size <= 8u;
match size {
1u => f(&[n as u8]),
2u => f(&[(n >> 8) as u8,
n as u8]),
4u => f(&[(n >> 24) as u8,
(n >> 16) as u8,
(n >> 8) as u8,
n as u8]),
8u => f(&[(n >> 56) as u8,
(n >> 48) as u8,
(n >> 40) as u8,
(n >> 32) as u8,
(n >> 24) as u8,
(n >> 16) as u8,
(n >> 8) as u8,
n as u8]),
_ => {
let mut bytes: ~[u8] = ~[];
let mut i = size;
while i > 0u {
let shift = ((i - 1u) * 8u) as u64;
bytes.push((n >> shift) as u8);
i -= 1u;
}
f(bytes)
}
}
}
pub fn u64_from_be_bytes(data: &[const u8],
start: uint, size: uint) -> u64 {
let mut sz = size;
assert (sz <= 8u);
let mut val = 0_u64;
let mut pos = start;
while sz > 0u {
sz -= 1u;
val += (data[pos] as u64) << ((sz * 8u) as u64);
pos += 1u;
}
return val;
}
// FIXME: #3048 combine trait+impl (or just move these to
// default methods on writer)
/// Generic utility functions defined on writers.
pub trait WriterUtil {
/// Write a single utf-8 encoded char.
fn write_char(&self, ch: char);
/// Write every char in the given str, encoded as utf-8.
fn write_str(&self, s: &str);
/// Write the given str, as utf-8, followed by '\n'.
fn write_line(&self, s: &str);
/// Write the result of passing n through `int::to_str_bytes`.
fn write_int(&self, n: int);
/// Write the result of passing n through `uint::to_str_bytes`.
fn write_uint(&self, n: uint);
/// Write a little-endian uint (number of bytes depends on system).
fn write_le_uint(&self, n: uint);
/// Write a little-endian int (number of bytes depends on system).
fn write_le_int(&self, n: int);
/// Write a big-endian uint (number of bytes depends on system).
fn write_be_uint(&self, n: uint);
/// Write a big-endian int (number of bytes depends on system).
fn write_be_int(&self, n: int);
/// Write a big-endian u64 (8 bytes).
fn write_be_u64(&self, n: u64);
/// Write a big-endian u32 (4 bytes).
fn write_be_u32(&self, n: u32);
/// Write a big-endian u16 (2 bytes).
fn write_be_u16(&self, n: u16);
/// Write a big-endian i64 (8 bytes).
fn write_be_i64(&self, n: i64);
/// Write a big-endian i32 (4 bytes).
fn write_be_i32(&self, n: i32);
/// Write a big-endian i16 (2 bytes).
fn write_be_i16(&self, n: i16);
/// Write a little-endian u64 (8 bytes).
fn write_le_u64(&self, n: u64);
/// Write a little-endian u32 (4 bytes).
fn write_le_u32(&self, n: u32);
/// Write a little-endian u16 (2 bytes).
fn write_le_u16(&self, n: u16);
/// Write a little-endian i64 (8 bytes).
fn write_le_i64(&self, n: i64);
/// Write a little-endian i32 (4 bytes).
fn write_le_i32(&self, n: i32);
/// Write a little-endian i16 (2 bytes).
fn write_le_i16(&self, n: i16);
/// Write a u8 (1 byte).
fn write_u8(&self, n: u8);
/// Write a i8 (1 byte).
fn write_i8(&self, n: i8);
}
impl<T: Writer> T : WriterUtil {
fn write_char(&self, ch: char) {
if ch as uint < 128u {
self.write(&[ch as u8]);
} else {
self.write_str(str::from_char(ch));
}
}
fn write_str(&self, s: &str) { str::byte_slice(s, |v| self.write(v)) }
fn write_line(&self, s: &str) {
self.write_str(s);
self.write_str(&"\n");
}
fn write_int(&self, n: int) {
int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
}
fn write_uint(&self, n: uint) {
uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
}
fn write_le_uint(&self, n: uint) {
u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v))
}
fn write_le_int(&self, n: int) {
u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v))
}
fn write_be_uint(&self, n: uint) {
u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v))
}
fn write_be_int(&self, n: int) {
u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v))
}
fn write_be_u64(&self, n: u64) {
u64_to_be_bytes(n, 8u, |v| self.write(v))
}
fn write_be_u32(&self, n: u32) {
u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
}
fn write_be_u16(&self, n: u16) {
u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
}
fn write_be_i64(&self, n: i64) {
u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
}
fn write_be_i32(&self, n: i32) {
u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
}
fn write_be_i16(&self, n: i16) {
u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
}
fn write_le_u64(&self, n: u64) {
u64_to_le_bytes(n, 8u, |v| self.write(v))
}
fn write_le_u32(&self, n: u32) {
u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
}
fn write_le_u16(&self, n: u16) {
u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
}
fn write_le_i64(&self, n: i64) {
u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
}
fn write_le_i32(&self, n: i32) {
u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
}
fn write_le_i16(&self, n: i16) {
u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
}
fn write_u8(&self, n: u8) { self.write([n]) }
fn write_i8(&self, n: i8) { self.write([n as u8]) }
}
#[allow(non_implicitly_copyable_typarams)]
pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<Writer, ~str> {
mk_file_writer(path, flags).chain(|w| result::Ok(w))
}
// FIXME: fileflags // #2004
pub fn buffered_file_writer(path: &Path) -> Result<Writer, ~str> {
unsafe {
let f = do os::as_c_charp(path.to_str()) |pathbuf| {
do os::as_c_charp("w") |modebuf| {
libc::fopen(pathbuf, modebuf)
}
};
return if f as uint == 0u { result::Err(~"error opening "
+ path.to_str()) }
else { result::Ok(FILE_writer(f, true)) }
}
}
// FIXME (#2004) it would be great if this could be a const
// FIXME (#2004) why are these different from the way stdin() is
// implemented?
pub fn stdout() -> Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) }
pub fn stderr() -> Writer { fd_writer(libc::STDERR_FILENO as c_int, false) }
pub fn print(s: &str) { stdout().write_str(s); }
pub fn println(s: &str) { stdout().write_line(s); }
pub struct BytesWriter {
bytes: DVec<u8>,
mut pos: uint,
}