]> git.lizzy.rs Git - rust.git/blob - src/libextra/terminfo/parm.rs
Fix bug in `match`ing struct patterns
[rust.git] / src / libextra / terminfo / parm.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Parameterized string expansion
12
13 use std::{char, vec, util};
14 use std::num::strconv::{SignNone,SignNeg,SignAll,int_to_str_bytes_common};
15 use std::iterator::IteratorUtil;
16
17 #[deriving(Eq)]
18 enum States {
19     Nothing,
20     Percent,
21     SetVar,
22     GetVar,
23     PushParam,
24     CharConstant,
25     CharClose,
26     IntConstant(int),
27     FormatPattern(Flags, FormatState),
28     SeekIfElse(int),
29     SeekIfElsePercent(int),
30     SeekIfEnd(int),
31     SeekIfEndPercent(int)
32 }
33
34 #[deriving(Eq)]
35 enum FormatState {
36     FormatStateFlags,
37     FormatStateWidth,
38     FormatStatePrecision
39 }
40
41 /// Types of parameters a capability can use
42 #[deriving(Clone)]
43 pub enum Param {
44     String(~str),
45     Number(int)
46 }
47
48 /// Container for static and dynamic variable arrays
49 pub struct Variables {
50     /// Static variables A-Z
51     sta: [Param, ..26],
52     /// Dynamic variables a-z
53     dyn: [Param, ..26]
54 }
55
56 impl Variables {
57     /// Return a new zero-initialized Variables
58     pub fn new() -> Variables {
59         Variables {
60             sta: [
61                 Number(0), Number(0), Number(0), Number(0), Number(0),
62                 Number(0), Number(0), Number(0), Number(0), Number(0),
63                 Number(0), Number(0), Number(0), Number(0), Number(0),
64                 Number(0), Number(0), Number(0), Number(0), Number(0),
65                 Number(0), Number(0), Number(0), Number(0), Number(0),
66                 Number(0),
67             ],
68             dyn: [
69                 Number(0), Number(0), Number(0), Number(0), Number(0),
70                 Number(0), Number(0), Number(0), Number(0), Number(0),
71                 Number(0), Number(0), Number(0), Number(0), Number(0),
72                 Number(0), Number(0), Number(0), Number(0), Number(0),
73                 Number(0), Number(0), Number(0), Number(0), Number(0),
74                 Number(0),
75             ],
76         }
77     }
78 }
79
80 /**
81   Expand a parameterized capability
82
83   # Arguments
84   * `cap`    - string to expand
85   * `params` - vector of params for %p1 etc
86   * `vars`   - Variables struct for %Pa etc
87
88   To be compatible with ncurses, `vars` should be the same between calls to `expand` for
89   multiple capabilities for the same terminal.
90   */
91 pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
92     -> Result<~[u8], ~str> {
93     let mut state = Nothing;
94
95     // expanded cap will only rarely be larger than the cap itself
96     let mut output = vec::with_capacity(cap.len());
97
98     let mut stack: ~[Param] = ~[];
99
100     // Copy parameters into a local vector for mutability
101     let mut mparams = [
102         Number(0), Number(0), Number(0), Number(0), Number(0),
103         Number(0), Number(0), Number(0), Number(0),
104     ];
105     for (dst, src) in mparams.mut_iter().zip(params.iter()) {
106         *dst = (*src).clone();
107     }
108
109     for c in cap.iter().transform(|&x| x) {
110         let cur = c as char;
111         let mut old_state = state;
112         match state {
113             Nothing => {
114                 if cur == '%' {
115                     state = Percent;
116                 } else {
117                     output.push(c);
118                 }
119             },
120             Percent => {
121                 match cur {
122                     '%' => { output.push(c); state = Nothing },
123                     'c' => if stack.len() > 0 {
124                         match stack.pop() {
125                             // if c is 0, use 0200 (128) for ncurses compatibility
126                             Number(c) => output.push(if c == 0 { 128 } else { c } as u8),
127                             _       => return Err(~"a non-char was used with %c")
128                         }
129                     } else { return Err(~"stack is empty") },
130                     'p' => state = PushParam,
131                     'P' => state = SetVar,
132                     'g' => state = GetVar,
133                     '\'' => state = CharConstant,
134                     '{' => state = IntConstant(0),
135                     'l' => if stack.len() > 0 {
136                         match stack.pop() {
137                             String(s) => stack.push(Number(s.len() as int)),
138                             _         => return Err(~"a non-str was used with %l")
139                         }
140                     } else { return Err(~"stack is empty") },
141                     '+' => if stack.len() > 1 {
142                         match (stack.pop(), stack.pop()) {
143                             (Number(y), Number(x)) => stack.push(Number(x + y)),
144                             _ => return Err(~"non-numbers on stack with +")
145                         }
146                     } else { return Err(~"stack is empty") },
147                     '-' => if stack.len() > 1 {
148                         match (stack.pop(), stack.pop()) {
149                             (Number(y), Number(x)) => stack.push(Number(x - y)),
150                             _ => return Err(~"non-numbers on stack with -")
151                         }
152                     } else { return Err(~"stack is empty") },
153                     '*' => if stack.len() > 1 {
154                         match (stack.pop(), stack.pop()) {
155                             (Number(y), Number(x)) => stack.push(Number(x * y)),
156                             _ => return Err(~"non-numbers on stack with *")
157                         }
158                     } else { return Err(~"stack is empty") },
159                     '/' => if stack.len() > 1 {
160                         match (stack.pop(), stack.pop()) {
161                             (Number(y), Number(x)) => stack.push(Number(x / y)),
162                             _ => return Err(~"non-numbers on stack with /")
163                         }
164                     } else { return Err(~"stack is empty") },
165                     'm' => if stack.len() > 1 {
166                         match (stack.pop(), stack.pop()) {
167                             (Number(y), Number(x)) => stack.push(Number(x % y)),
168                             _ => return Err(~"non-numbers on stack with %")
169                         }
170                     } else { return Err(~"stack is empty") },
171                     '&' => if stack.len() > 1 {
172                         match (stack.pop(), stack.pop()) {
173                             (Number(y), Number(x)) => stack.push(Number(x & y)),
174                             _ => return Err(~"non-numbers on stack with &")
175                         }
176                     } else { return Err(~"stack is empty") },
177                     '|' => if stack.len() > 1 {
178                         match (stack.pop(), stack.pop()) {
179                             (Number(y), Number(x)) => stack.push(Number(x | y)),
180                             _ => return Err(~"non-numbers on stack with |")
181                         }
182                     } else { return Err(~"stack is empty") },
183                     '^' => if stack.len() > 1 {
184                         match (stack.pop(), stack.pop()) {
185                             (Number(y), Number(x)) => stack.push(Number(x ^ y)),
186                             _ => return Err(~"non-numbers on stack with ^")
187                         }
188                     } else { return Err(~"stack is empty") },
189                     '=' => if stack.len() > 1 {
190                         match (stack.pop(), stack.pop()) {
191                             (Number(y), Number(x)) => stack.push(Number(if x == y { 1 }
192                                                                         else { 0 })),
193                             _ => return Err(~"non-numbers on stack with =")
194                         }
195                     } else { return Err(~"stack is empty") },
196                     '>' => if stack.len() > 1 {
197                         match (stack.pop(), stack.pop()) {
198                             (Number(y), Number(x)) => stack.push(Number(if x > y { 1 }
199                                                                         else { 0 })),
200                             _ => return Err(~"non-numbers on stack with >")
201                         }
202                     } else { return Err(~"stack is empty") },
203                     '<' => if stack.len() > 1 {
204                         match (stack.pop(), stack.pop()) {
205                             (Number(y), Number(x)) => stack.push(Number(if x < y { 1 }
206                                                                         else { 0 })),
207                             _ => return Err(~"non-numbers on stack with <")
208                         }
209                     } else { return Err(~"stack is empty") },
210                     'A' => if stack.len() > 1 {
211                         match (stack.pop(), stack.pop()) {
212                             (Number(0), Number(_)) => stack.push(Number(0)),
213                             (Number(_), Number(0)) => stack.push(Number(0)),
214                             (Number(_), Number(_)) => stack.push(Number(1)),
215                             _ => return Err(~"non-numbers on stack with logical and")
216                         }
217                     } else { return Err(~"stack is empty") },
218                     'O' => if stack.len() > 1 {
219                         match (stack.pop(), stack.pop()) {
220                             (Number(0), Number(0)) => stack.push(Number(0)),
221                             (Number(_), Number(_)) => stack.push(Number(1)),
222                             _ => return Err(~"non-numbers on stack with logical or")
223                         }
224                     } else { return Err(~"stack is empty") },
225                     '!' => if stack.len() > 0 {
226                         match stack.pop() {
227                             Number(0) => stack.push(Number(1)),
228                             Number(_) => stack.push(Number(0)),
229                             _ => return Err(~"non-number on stack with logical not")
230                         }
231                     } else { return Err(~"stack is empty") },
232                     '~' => if stack.len() > 0 {
233                         match stack.pop() {
234                             Number(x) => stack.push(Number(!x)),
235                             _         => return Err(~"non-number on stack with %~")
236                         }
237                     } else { return Err(~"stack is empty") },
238                     'i' => match (mparams[0].clone(), mparams[1].clone()) {
239                         (Number(x), Number(y)) => {
240                             mparams[0] = Number(x+1);
241                             mparams[1] = Number(y+1);
242                         },
243                         (_, _) => return Err(~"first two params not numbers with %i")
244                     },
245
246                     // printf-style support for %doxXs
247                     'd'|'o'|'x'|'X'|'s' => if stack.len() > 0 {
248                         let flags = Flags::new();
249                         let res = format(stack.pop(), FormatOp::from_char(cur), flags);
250                         if res.is_err() { return res }
251                         output.push_all(res.unwrap())
252                     } else { return Err(~"stack is empty") },
253                     ':'|'#'|' '|'.'|'0'..'9' => {
254                         let mut flags = Flags::new();
255                         let mut fstate = FormatStateFlags;
256                         match cur {
257                             ':' => (),
258                             '#' => flags.alternate = true,
259                             ' ' => flags.space = true,
260                             '.' => fstate = FormatStatePrecision,
261                             '0'..'9' => {
262                                 flags.width = (cur - '0') as uint;
263                                 fstate = FormatStateWidth;
264                             }
265                             _ => util::unreachable()
266                         }
267                         state = FormatPattern(flags, fstate);
268                     }
269
270                     // conditionals
271                     '?' => (),
272                     't' => if stack.len() > 0 {
273                         match stack.pop() {
274                             Number(0) => state = SeekIfElse(0),
275                             Number(_) => (),
276                             _         => return Err(~"non-number on stack with conditional")
277                         }
278                     } else { return Err(~"stack is empty") },
279                     'e' => state = SeekIfEnd(0),
280                     ';' => (),
281
282                     _ => return Err(fmt!("unrecognized format option %c", cur))
283                 }
284             },
285             PushParam => {
286                 // params are 1-indexed
287                 stack.push(mparams[match char::to_digit(cur, 10) {
288                     Some(d) => d - 1,
289                     None => return Err(~"bad param number")
290                 }].clone());
291             },
292             SetVar => {
293                 if cur >= 'A' && cur <= 'Z' {
294                     if stack.len() > 0 {
295                         let idx = (cur as u8) - ('A' as u8);
296                         vars.sta[idx] = stack.pop();
297                     } else { return Err(~"stack is empty") }
298                 } else if cur >= 'a' && cur <= 'z' {
299                     if stack.len() > 0 {
300                         let idx = (cur as u8) - ('a' as u8);
301                         vars.dyn[idx] = stack.pop();
302                     } else { return Err(~"stack is empty") }
303                 } else {
304                     return Err(~"bad variable name in %P");
305                 }
306             },
307             GetVar => {
308                 if cur >= 'A' && cur <= 'Z' {
309                     let idx = (cur as u8) - ('A' as u8);
310                     stack.push(vars.sta[idx].clone());
311                 } else if cur >= 'a' && cur <= 'z' {
312                     let idx = (cur as u8) - ('a' as u8);
313                     stack.push(vars.dyn[idx].clone());
314                 } else {
315                     return Err(~"bad variable name in %g");
316                 }
317             },
318             CharConstant => {
319                 stack.push(Number(c as int));
320                 state = CharClose;
321             },
322             CharClose => {
323                 if cur != '\'' {
324                     return Err(~"malformed character constant");
325                 }
326             },
327             IntConstant(i) => {
328                 match cur {
329                     '}' => {
330                         stack.push(Number(i));
331                         state = Nothing;
332                     }
333                     '0'..'9' => {
334                         state = IntConstant(i*10 + ((cur - '0') as int));
335                         old_state = Nothing;
336                     }
337                     _ => return Err(~"bad int constant")
338                 }
339             }
340             FormatPattern(ref mut flags, ref mut fstate) => {
341                 old_state = Nothing;
342                 match (*fstate, cur) {
343                     (_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if stack.len() > 0 {
344                         let res = format(stack.pop(), FormatOp::from_char(cur), *flags);
345                         if res.is_err() { return res }
346                         output.push_all(res.unwrap());
347                         old_state = state; // will cause state to go to Nothing
348                     } else { return Err(~"stack is empty") },
349                     (FormatStateFlags,'#') => {
350                         flags.alternate = true;
351                     }
352                     (FormatStateFlags,'-') => {
353                         flags.left = true;
354                     }
355                     (FormatStateFlags,'+') => {
356                         flags.sign = true;
357                     }
358                     (FormatStateFlags,' ') => {
359                         flags.space = true;
360                     }
361                     (FormatStateFlags,'0'..'9') => {
362                         flags.width = (cur - '0') as uint;
363                         *fstate = FormatStateWidth;
364                     }
365                     (FormatStateFlags,'.') => {
366                         *fstate = FormatStatePrecision;
367                     }
368                     (FormatStateWidth,'0'..'9') => {
369                         let old = flags.width;
370                         flags.width = flags.width * 10 + ((cur - '0') as uint);
371                         if flags.width < old { return Err(~"format width overflow") }
372                     }
373                     (FormatStateWidth,'.') => {
374                         *fstate = FormatStatePrecision;
375                     }
376                     (FormatStatePrecision,'0'..'9') => {
377                         let old = flags.precision;
378                         flags.precision = flags.precision * 10 + ((cur - '0') as uint);
379                         if flags.precision < old { return Err(~"format precision overflow") }
380                     }
381                     _ => return Err(~"invalid format specifier")
382                 }
383             }
384             SeekIfElse(level) => {
385                 if cur == '%' {
386                     state = SeekIfElsePercent(level);
387                 }
388                 old_state = Nothing;
389             }
390             SeekIfElsePercent(level) => {
391                 if cur == ';' {
392                     if level == 0 {
393                         state = Nothing;
394                     } else {
395                         state = SeekIfElse(level-1);
396                     }
397                 } else if cur == 'e' && level == 0 {
398                     state = Nothing;
399                 } else if cur == '?' {
400                     state = SeekIfElse(level+1);
401                 } else {
402                     state = SeekIfElse(level);
403                 }
404             }
405             SeekIfEnd(level) => {
406                 if cur == '%' {
407                     state = SeekIfEndPercent(level);
408                 }
409                 old_state = Nothing;
410             }
411             SeekIfEndPercent(level) => {
412                 if cur == ';' {
413                     if level == 0 {
414                         state = Nothing;
415                     } else {
416                         state = SeekIfEnd(level-1);
417                     }
418                 } else if cur == '?' {
419                     state = SeekIfEnd(level+1);
420                 } else {
421                     state = SeekIfEnd(level);
422                 }
423             }
424         }
425         if state == old_state {
426             state = Nothing;
427         }
428     }
429     Ok(output)
430 }
431
432 #[deriving(Eq)]
433 priv struct Flags {
434     width: uint,
435     precision: uint,
436     alternate: bool,
437     left: bool,
438     sign: bool,
439     space: bool
440 }
441
442 impl Flags {
443     priv fn new() -> Flags {
444         Flags{ width: 0, precision: 0, alternate: false,
445                left: false, sign: false, space: false }
446     }
447 }
448
449 priv enum FormatOp {
450     FormatDigit,
451     FormatOctal,
452     FormatHex,
453     FormatHEX,
454     FormatString
455 }
456
457 impl FormatOp {
458     priv fn from_char(c: char) -> FormatOp {
459         match c {
460             'd' => FormatDigit,
461             'o' => FormatOctal,
462             'x' => FormatHex,
463             'X' => FormatHEX,
464             's' => FormatString,
465             _ => fail!("bad FormatOp char")
466         }
467     }
468     priv fn to_char(self) -> char {
469         match self {
470             FormatDigit => 'd',
471             FormatOctal => 'o',
472             FormatHex => 'x',
473             FormatHEX => 'X',
474             FormatString => 's'
475         }
476     }
477 }
478
479 priv fn format(val: Param, op: FormatOp, flags: Flags) -> Result<~[u8],~str> {
480     let mut s = match val {
481         Number(d) => {
482             match op {
483                 FormatString => {
484                     return Err(~"non-number on stack with %s")
485                 }
486                 _ => {
487                     let radix = match op {
488                         FormatDigit => 10,
489                         FormatOctal => 8,
490                         FormatHex|FormatHEX => 16,
491                         FormatString => util::unreachable()
492                     };
493                     let mut s = ~[];
494                     match op {
495                         FormatDigit => {
496                             let sign = if flags.sign { SignAll } else { SignNeg };
497                             do int_to_str_bytes_common(d, radix, sign) |c| {
498                                 s.push(c);
499                             }
500                         }
501                         _ => {
502                             do int_to_str_bytes_common(d as uint, radix, SignNone) |c| {
503                                 s.push(c);
504                             }
505                         }
506                     };
507                     if flags.precision > s.len() {
508                         let mut s_ = vec::with_capacity(flags.precision);
509                         let n = flags.precision - s.len();
510                         s_.grow(n, &('0' as u8));
511                         s_.push_all_move(s);
512                         s = s_;
513                     }
514                     assert!(!s.is_empty(), "string conversion produced empty result");
515                     match op {
516                         FormatDigit => {
517                             if flags.space && !(s[0] == '-' as u8 || s[0] == '+' as u8) {
518                                 s.unshift(' ' as u8);
519                             }
520                         }
521                         FormatOctal => {
522                             if flags.alternate && s[0] != '0' as u8 {
523                                 s.unshift('0' as u8);
524                             }
525                         }
526                         FormatHex => {
527                             if flags.alternate {
528                                 let s_ = util::replace(&mut s, ~['0' as u8, 'x' as u8]);
529                                 s.push_all_move(s_);
530                             }
531                         }
532                         FormatHEX => {
533                             s = s.into_ascii().to_upper().into_bytes();
534                             if flags.alternate {
535                                 let s_ = util::replace(&mut s, ~['0' as u8, 'X' as u8]);
536                                 s.push_all_move(s_);
537                             }
538                         }
539                         FormatString => util::unreachable()
540                     }
541                     s
542                 }
543             }
544         }
545         String(s) => {
546             match op {
547                 FormatString => {
548                     let mut s = s.to_bytes_with_null();
549                     s.pop(); // remove the null
550                     if flags.precision > 0 && flags.precision < s.len() {
551                         s.truncate(flags.precision);
552                     }
553                     s
554                 }
555                 _ => {
556                     return Err(fmt!("non-string on stack with %%%c", op.to_char()))
557                 }
558             }
559         }
560     };
561     if flags.width > s.len() {
562         let n = flags.width - s.len();
563         if flags.left {
564             s.grow(n, &(' ' as u8));
565         } else {
566             let mut s_ = vec::with_capacity(flags.width);
567             s_.grow(n, &(' ' as u8));
568             s_.push_all_move(s);
569             s = s_;
570         }
571     }
572     Ok(s)
573 }
574
575 #[cfg(test)]
576 mod test {
577     use super::*;
578     use std::result::Ok;
579
580     #[test]
581     fn test_basic_setabf() {
582         let s = bytes!("\\E[48;5;%p1%dm");
583         assert_eq!(expand(s, [Number(1)], &mut Variables::new()).unwrap(),
584                    bytes!("\\E[48;5;1m").to_owned());
585     }
586
587     #[test]
588     fn test_multiple_int_constants() {
589         assert_eq!(expand(bytes!("%{1}%{2}%d%d"), [], &mut Variables::new()).unwrap(),
590                    bytes!("21").to_owned());
591     }
592
593     #[test]
594     fn test_op_i() {
595         let mut vars = Variables::new();
596         assert_eq!(expand(bytes!("%p1%d%p2%d%p3%d%i%p1%d%p2%d%p3%d"),
597                           [Number(1),Number(2),Number(3)], &mut vars),
598                    Ok(bytes!("123233").to_owned()));
599         assert_eq!(expand(bytes!("%p1%d%p2%d%i%p1%d%p2%d"), [], &mut vars),
600                    Ok(bytes!("0011").to_owned()));
601     }
602
603     #[test]
604     fn test_param_stack_failure_conditions() {
605         let mut varstruct = Variables::new();
606         let vars = &mut varstruct;
607         let caps = ["%d", "%c", "%s", "%Pa", "%l", "%!", "%~"];
608         for cap in caps.iter() {
609             let res = expand(cap.as_bytes(), [], vars);
610             assert!(res.is_err(),
611                     "Op %s succeeded incorrectly with 0 stack entries", *cap);
612             let p = if *cap == "%s" || *cap == "%l" { String(~"foo") } else { Number(97) };
613             let res = expand((bytes!("%p1")).to_owned() + cap.as_bytes(), [p], vars);
614             assert!(res.is_ok(),
615                     "Op %s failed with 1 stack entry: %s", *cap, res.unwrap_err());
616         }
617         let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"];
618         for cap in caps.iter() {
619             let res = expand(cap.as_bytes(), [], vars);
620             assert!(res.is_err(),
621                     "Binop %s succeeded incorrectly with 0 stack entries", *cap);
622             let res = expand((bytes!("%{1}")).to_owned() + cap.as_bytes(), [], vars);
623             assert!(res.is_err(),
624                     "Binop %s succeeded incorrectly with 1 stack entry", *cap);
625             let res = expand((bytes!("%{1}%{2}")).to_owned() + cap.as_bytes(), [], vars);
626             assert!(res.is_ok(),
627                     "Binop %s failed with 2 stack entries: %s", *cap, res.unwrap_err());
628         }
629     }
630
631     #[test]
632     fn test_push_bad_param() {
633         assert!(expand(bytes!("%pa"), [], &mut Variables::new()).is_err());
634     }
635
636     #[test]
637     fn test_comparison_ops() {
638         let v = [('<', [1u8, 0u8, 0u8]), ('=', [0u8, 1u8, 0u8]), ('>', [0u8, 0u8, 1u8])];
639         for &(op, bs) in v.iter() {
640             let s = fmt!("%%{1}%%{2}%%%c%%d", op);
641             let res = expand(s.as_bytes(), [], &mut Variables::new());
642             assert!(res.is_ok(), res.unwrap_err());
643             assert_eq!(res.unwrap(), ~['0' as u8 + bs[0]]);
644             let s = fmt!("%%{1}%%{1}%%%c%%d", op);
645             let res = expand(s.as_bytes(), [], &mut Variables::new());
646             assert!(res.is_ok(), res.unwrap_err());
647             assert_eq!(res.unwrap(), ~['0' as u8 + bs[1]]);
648             let s = fmt!("%%{2}%%{1}%%%c%%d", op);
649             let res = expand(s.as_bytes(), [], &mut Variables::new());
650             assert!(res.is_ok(), res.unwrap_err());
651             assert_eq!(res.unwrap(), ~['0' as u8 + bs[2]]);
652         }
653     }
654
655     #[test]
656     fn test_conditionals() {
657         let mut vars = Variables::new();
658         let s = bytes!("\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m");
659         let res = expand(s, [Number(1)], &mut vars);
660         assert!(res.is_ok(), res.unwrap_err());
661         assert_eq!(res.unwrap(), bytes!("\\E[31m").to_owned());
662         let res = expand(s, [Number(8)], &mut vars);
663         assert!(res.is_ok(), res.unwrap_err());
664         assert_eq!(res.unwrap(), bytes!("\\E[90m").to_owned());
665         let res = expand(s, [Number(42)], &mut vars);
666         assert!(res.is_ok(), res.unwrap_err());
667         assert_eq!(res.unwrap(), bytes!("\\E[38;5;42m").to_owned());
668     }
669
670     #[test]
671     fn test_format() {
672         let mut varstruct = Variables::new();
673         let vars = &mut varstruct;
674         assert_eq!(expand(bytes!("%p1%s%p2%2s%p3%2s%p4%.2s"),
675                           [String(~"foo"), String(~"foo"), String(~"f"), String(~"foo")], vars),
676                    Ok(bytes!("foofoo ffo").to_owned()));
677         assert_eq!(expand(bytes!("%p1%:-4.2s"), [String(~"foo")], vars),
678                    Ok(bytes!("fo  ").to_owned()));
679
680         assert_eq!(expand(bytes!("%p1%d%p1%.3d%p1%5d%p1%:+d"), [Number(1)], vars),
681                    Ok(bytes!("1001    1+1").to_owned()));
682         assert_eq!(expand(bytes!("%p1%o%p1%#o%p2%6.4x%p2%#6.4X"), [Number(15), Number(27)], vars),
683                    Ok(bytes!("17017  001b0X001B").to_owned()));
684     }
685 }