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
#![allow(unused_variables)]
use any;
use cell::{Cell, Ref, RefMut};
use iter::{Iterator, IteratorExt, range};
use kinds::{Copy, Sized};
use mem;
use option::Option;
use option::Option::{Some, None};
use ops::{Deref, FnOnce};
use result::Result::{Ok, Err};
use result;
use slice::SliceExt;
use slice;
use str::{StrExt, Utf8Error};
pub use self::num::radix;
pub use self::num::Radix;
pub use self::num::RadixFmt;
mod num;
mod float;
pub mod rt;
#[experimental = "core and I/O reconciliation may alter this definition"]
pub type Result = result::Result<(), Error>;
#[experimental = "core and I/O reconciliation may alter this definition"]
#[deriving(Copy)]
pub struct Error;
#[experimental = "waiting for core and I/O reconciliation"]
pub trait FormatWriter {
fn write(&mut self, bytes: &[u8]) -> Result;
fn write_fmt(&mut self, args: Arguments) -> Result { write(self, args) }
}
#[unstable = "name may change and implemented traits are also unstable"]
pub struct Formatter<'a> {
flags: uint,
fill: char,
align: rt::Alignment,
width: Option<uint>,
precision: Option<uint>,
buf: &'a mut (FormatWriter+'a),
curarg: slice::Iter<'a, Argument<'a>>,
args: &'a [Argument<'a>],
}
enum Void {}
#[experimental = "implementation detail of the `format_args!` macro"]
#[deriving(Copy)]
pub struct Argument<'a> {
value: &'a Void,
formatter: fn(&Void, &mut Formatter) -> Result,
}
impl<'a> Argument<'a> {
#[inline(never)]
fn show_uint(x: &uint, f: &mut Formatter) -> Result {
Show::fmt(x, f)
}
fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter) -> Result) -> Argument<'b> {
unsafe {
Argument {
formatter: mem::transmute(f),
value: mem::transmute(x)
}
}
}
fn from_uint(x: &uint) -> Argument {
Argument::new(x, Argument::show_uint)
}
fn as_uint(&self) -> Option<uint> {
if self.formatter as uint == Argument::show_uint as uint {
Some(unsafe { *(self.value as *const _ as *const uint) })
} else {
None
}
}
}
impl<'a> Arguments<'a> {
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn new(pieces: &'a [&'a str],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: None,
args: args
}
}
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn with_placeholders(pieces: &'a [&'a str],
fmt: &'a [rt::Argument<'a>],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: pieces,
fmt: Some(fmt),
args: args
}
}
}
#[stable]
#[deriving(Copy)]
pub struct Arguments<'a> {
pieces: &'a [&'a str],
fmt: Option<&'a [rt::Argument<'a>]>,
args: &'a [Argument<'a>],
}
impl<'a> Show for Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result {
write(fmt.buf, *self)
}
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Octal for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Binary for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerHex for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperHex for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Pointer for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerExp for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperExp for Sized? {
fn fmt(&self, &mut Formatter) -> Result;
}
static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument {
position: rt::ArgumentNext,
format: rt::FormatSpec {
fill: ' ',
align: rt::AlignUnknown,
flags: 0,
precision: rt::CountImplied,
width: rt::CountImplied,
}
};
#[experimental = "libcore and I/O have yet to be reconciled, and this is an \
implementation detail which should not otherwise be exported"]
pub fn write(output: &mut FormatWriter, args: Arguments) -> Result {
let mut formatter = Formatter {
flags: 0,
width: None,
precision: None,
buf: output,
align: rt::AlignUnknown,
fill: ' ',
args: args.args,
curarg: args.args.iter(),
};
let mut pieces = args.pieces.iter();
match args.fmt {
None => {
for _ in range(0, args.args.len()) {
try!(formatter.buf.write(pieces.next().unwrap().as_bytes()));
try!(formatter.run(&DEFAULT_ARGUMENT));
}
}
Some(fmt) => {
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write(piece.as_bytes()));
try!(formatter.run(arg));
}
}
}
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write(piece.as_bytes()));
}
None => {}
}
Ok(())
}
impl<'a> Formatter<'a> {
fn run(&mut self, arg: &rt::Argument) -> Result {
self.fill = arg.format.fill;
self.align = arg.format.align;
self.flags = arg.format.flags;
self.width = self.getcount(&arg.format.width);
self.precision = self.getcount(&arg.format.precision);
let value = match arg.position {
rt::ArgumentNext => { *self.curarg.next().unwrap() }
rt::ArgumentIs(i) => self.args[i],
};
(value.formatter)(value.value, self)
}
fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
match *cnt {
rt::CountIs(n) => Some(n),
rt::CountImplied => None,
rt::CountIsParam(i) => {
self.args[i].as_uint()
}
rt::CountIsNextParam => {
self.curarg.next().and_then(|arg| arg.as_uint())
}
}
}
#[unstable = "definition may change slightly over time"]
pub fn pad_integral(&mut self,
is_positive: bool,
prefix: &str,
buf: &[u8])
-> Result {
use char::Char;
use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
let mut width = buf.len();
let mut sign = None;
if !is_positive {
sign = Some('-'); width += 1;
} else if self.flags & (1 << (FlagSignPlus as uint)) != 0 {
sign = Some('+'); width += 1;
}
let mut prefixed = false;
if self.flags & (1 << (FlagAlternate as uint)) != 0 {
prefixed = true; width += prefix.char_len();
}
let write_prefix = |&: f: &mut Formatter| {
for c in sign.into_iter() {
let mut b = [0, ..4];
let n = c.encode_utf8(&mut b).unwrap_or(0);
try!(f.buf.write(b[..n]));
}
if prefixed { f.buf.write(prefix.as_bytes()) }
else { Ok(()) }
};
match self.width {
None => {
try!(write_prefix(self)); self.buf.write(buf)
}
Some(min) if width >= min => {
try!(write_prefix(self)); self.buf.write(buf)
}
Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint)) != 0 => {
self.fill = '0';
try!(write_prefix(self));
self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf))
}
Some(min) => {
self.with_padding(min - width, rt::AlignRight, |f| {
try!(write_prefix(f)); f.buf.write(buf)
})
}
}
}
#[unstable = "definition may change slightly over time"]
pub fn pad(&mut self, s: &str) -> Result {
if self.width.is_none() && self.precision.is_none() {
return self.buf.write(s.as_bytes());
}
match self.precision {
Some(max) => {
let char_len = s.char_len();
if char_len >= max {
let nchars = ::cmp::min(max, char_len);
return self.buf.write(s.slice_chars(0, nchars).as_bytes());
}
}
None => {}
}
match self.width {
None => self.buf.write(s.as_bytes()),
Some(width) if s.char_len() >= width => {
self.buf.write(s.as_bytes())
}
Some(width) => {
self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
me.buf.write(s.as_bytes())
})
}
}
}
fn with_padding<F>(&mut self, padding: uint, default: rt::Alignment, f: F) -> Result where
F: FnOnce(&mut Formatter) -> Result,
{
use char::Char;
let align = match self.align {
rt::AlignUnknown => default,
_ => self.align
};
let (pre_pad, post_pad) = match align {
rt::AlignLeft => (0u, padding),
rt::AlignRight | rt::AlignUnknown => (padding, 0u),
rt::AlignCenter => (padding / 2, (padding + 1) / 2),
};
let mut fill = [0u8, ..4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
for _ in range(0, pre_pad) {
try!(self.buf.write(fill[..len]));
}
try!(f(self));
for _ in range(0, post_pad) {
try!(self.buf.write(fill[..len]));
}
Ok(())
}
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write(&mut self, data: &[u8]) -> Result {
self.buf.write(data)
}
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write_fmt(&mut self, fmt: Arguments) -> Result {
write(self.buf, fmt)
}
#[experimental = "return type may change and method was just created"]
pub fn flags(&self) -> uint { self.flags }
#[unstable = "method was just created"]
pub fn fill(&self) -> char { self.fill }
#[unstable = "method was just created"]
pub fn align(&self) -> rt::Alignment { self.align }
#[unstable = "method was just created"]
pub fn width(&self) -> Option<uint> { self.width }
#[unstable = "method was just created"]
pub fn precision(&self) -> Option<uint> { self.precision }
}
impl Show for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
"an error occurred when formatting an argument".fmt(f)
}
}
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argument<'a, T>(f: fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
Argument::new(t, f)
}
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
Argument::from_uint(s)
}
impl<'a, Sized? T: Show> Show for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a, Sized? T: Show> Show for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a> Show for &'a (Show+'a) {
fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) }
}
impl Show for bool {
fn fmt(&self, f: &mut Formatter) -> Result {
Show::fmt(if *self { "true" } else { "false" }, f)
}
}
impl Show for str {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad(self)
}
}
impl Show for char {
fn fmt(&self, f: &mut Formatter) -> Result {
use char::Char;
let mut utf8 = [0u8, ..4];
let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
let s: &str = unsafe { mem::transmute(utf8[..amt]) };
Show::fmt(s, f)
}
}
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
f.flags |= 1 << (rt::FlagAlternate as uint);
LowerHex::fmt(&(*self as uint), f)
}
}
impl<T> Pointer for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(&**self as *const T), f)
}
}
macro_rules! floating { ($ty:ident) => {
impl Show for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpNone,
false,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
impl LowerExp for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpDec,
false,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
impl UpperExp for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpDec,
true,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
} }
floating! { f32 }
floating! { f64 }
impl<T> Show for *const T {
fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
}
impl<T> Show for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result { Pointer::fmt(self, f) }
}
macro_rules! peel {
($name:ident, $($other:ident,)*) => (tuple! { $($other,)* })
}
macro_rules! tuple {
() => ();
( $($name:ident,)+ ) => (
impl<$($name:Show),*> Show for ($($name,)*) {
#[allow(non_snake_case, unused_assignments)]
fn fmt(&self, f: &mut Formatter) -> Result {
try!(write!(f, "("));
let ($(ref $name,)*) = *self;
let mut n = 0i;
$(
if n > 0 {
try!(write!(f, ", "));
}
try!(write!(f, "{}", *$name));
n += 1;
)*
if n == 1 {
try!(write!(f, ","));
}
write!(f, ")")
}
}
peel! { $($name,)* }
)
}
tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, }
impl<'a> Show for &'a (any::Any+'a) {
fn fmt(&self, f: &mut Formatter) -> Result { f.pad("&Any") }
}
impl<T: Show> Show for [T] {
fn fmt(&self, f: &mut Formatter) -> Result {
if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
try!(write!(f, "["));
}
let mut is_first = true;
for x in self.iter() {
if is_first {
is_first = false;
} else {
try!(write!(f, ", "));
}
try!(write!(f, "{}", *x))
}
if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
try!(write!(f, "]"));
}
Ok(())
}
}
impl Show for () {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad("()")
}
}
impl<T: Copy + Show> Show for Cell<T> {
fn fmt(&self, f: &mut Formatter) -> Result {
write!(f, "Cell {{ value: {} }}", self.get())
}
}
impl<'b, T: Show> Show for Ref<'b, T> {
fn fmt(&self, f: &mut Formatter) -> Result {
(**self).fmt(f)
}
}
impl<'b, T: Show> Show for RefMut<'b, T> {
fn fmt(&self, f: &mut Formatter) -> Result {
(*(self.deref())).fmt(f)
}
}
impl Show for Utf8Error {
fn fmt(&self, f: &mut Formatter) -> Result {
match *self {
Utf8Error::InvalidByte(n) => {
write!(f, "invalid utf-8: invalid byte at index {}", n)
}
Utf8Error::TooShort => {
write!(f, "invalid utf-8: byte slice too short")
}
}
}
}