Skip to content

Commit 428abb3

Browse files
committed
fmt: simplify parse_fmt_string
1 parent 9e5a416 commit 428abb3

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

src/libcore/extfmt.rs

+24-22
Original file line numberDiff line numberDiff line change
@@ -154,39 +154,41 @@ pub mod ct {
154154
pub type ErrorFn = fn@(&str) -> ! ;
155155

156156
pub fn parse_fmt_string(s: &str, err: ErrorFn) -> ~[Piece] {
157-
let mut pieces: ~[Piece] = ~[];
158-
let lim = str::len(s);
159-
let mut buf = ~"";
160-
fn flush_buf(buf: ~str, pieces: &mut ~[Piece]) -> ~str {
161-
if buf.len() > 0 {
162-
let piece = PieceString(move buf);
163-
pieces.push(move piece);
157+
fn push_slice(ps: &mut ~[Piece], s: &str, from: uint, to: uint) {
158+
if to > from {
159+
ps.push(PieceString(s.slice(from, to)));
164160
}
165-
return ~"";
166161
}
162+
163+
let lim = s.len();
164+
let mut h = 0;
167165
let mut i = 0;
166+
let mut pieces = ~[];
167+
168168
while i < lim {
169-
let size = str::utf8_char_width(s[i]);
170-
let curr = str::slice(s, i, i+size);
171-
if curr == ~"%" {
169+
if s[i] == '%' as u8 {
172170
i += 1;
171+
173172
if i >= lim {
174173
err(~"unterminated conversion at end of string");
175-
}
176-
let curr2 = str::slice(s, i, i+1);
177-
if curr2 == ~"%" {
178-
buf += curr2;
174+
} else if s[i] == '%' as u8 {
175+
push_slice(&mut pieces, s, h, i);
179176
i += 1;
180177
} else {
181-
buf = flush_buf(move buf, &mut pieces);
182-
let rs = parse_conversion(s, i, lim, err);
183-
pieces.push(copy rs.val);
184-
i = rs.next;
178+
push_slice(&mut pieces, s, h, i - 1);
179+
let Parsed {val, next} = parse_conversion(s, i, lim, err);
180+
pieces.push(val);
181+
i = next;
185182
}
186-
} else { buf += curr; i += size; }
183+
184+
h = i;
185+
} else {
186+
i += str::utf8_char_width(s[i]);
187+
}
187188
}
188-
flush_buf(move buf, &mut pieces);
189-
move pieces
189+
190+
push_slice(&mut pieces, s, h, i);
191+
pieces
190192
}
191193
pub fn peek_num(s: &str, i: uint, lim: uint) ->
192194
Option<Parsed<uint>> {

0 commit comments

Comments
 (0)