@@ -247,12 +247,14 @@ pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
247247 debug ! ( "mk_printer {}" , linewidth) ;
248248 Printer {
249249 out,
250- buf_len : n,
250+ buf_max_len : n,
251251 margin : linewidth as isize ,
252252 space : linewidth as isize ,
253253 left : 0 ,
254254 right : 0 ,
255- buf : vec ! [ BufEntry { token: Token :: Eof , size: 0 } ; n] ,
255+ // Initialize a single entry; advance_right() will extend it on demand
256+ // up to `buf_max_len` elements.
257+ buf : vec ! [ BufEntry :: default ( ) ] ,
256258 left_total : 0 ,
257259 right_total : 0 ,
258260 scan_stack : VecDeque :: new ( ) ,
@@ -263,7 +265,7 @@ pub fn mk_printer<'a>(out: Box<io::Write+'a>, linewidth: usize) -> Printer<'a> {
263265
264266pub struct Printer < ' a > {
265267 out : Box < io:: Write +' a > ,
266- buf_len : usize ,
268+ buf_max_len : usize ,
267269 /// Width of lines we're constrained to
268270 margin : isize ,
269271 /// Number of spaces left on line
@@ -297,6 +299,12 @@ struct BufEntry {
297299 size : isize ,
298300}
299301
302+ impl Default for BufEntry {
303+ fn default ( ) -> Self {
304+ BufEntry { token : Token :: Eof , size : 0 }
305+ }
306+ }
307+
300308impl < ' a > Printer < ' a > {
301309 pub fn last_token ( & mut self ) -> Token {
302310 self . buf [ self . right ] . token . clone ( )
@@ -322,7 +330,9 @@ impl<'a> Printer<'a> {
322330 self . right_total = 1 ;
323331 self . left = 0 ;
324332 self . right = 0 ;
325- } else { self . advance_right ( ) ; }
333+ } else {
334+ self . advance_right ( ) ;
335+ }
326336 debug ! ( "pp Begin({})/buffer Vec<{},{}>" ,
327337 b. offset, self . left, self . right) ;
328338 self . buf [ self . right ] = BufEntry { token : token, size : -self . right_total } ;
@@ -349,7 +359,9 @@ impl<'a> Printer<'a> {
349359 self . right_total = 1 ;
350360 self . left = 0 ;
351361 self . right = 0 ;
352- } else { self . advance_right ( ) ; }
362+ } else {
363+ self . advance_right ( ) ;
364+ }
353365 debug ! ( "pp Break({})/buffer Vec<{},{}>" ,
354366 b. offset, self . left, self . right) ;
355367 self . check_stack ( 0 ) ;
@@ -408,7 +420,11 @@ impl<'a> Printer<'a> {
408420 }
409421 pub fn advance_right ( & mut self ) {
410422 self . right += 1 ;
411- self . right %= self . buf_len ;
423+ self . right %= self . buf_max_len ;
424+ // Extend the buf if necessary.
425+ if self . right == self . buf . len ( ) {
426+ self . buf . push ( BufEntry :: default ( ) ) ;
427+ }
412428 assert_ne ! ( self . right, self . left) ;
413429 }
414430 pub fn advance_left ( & mut self ) -> io:: Result < ( ) > {
@@ -438,7 +454,7 @@ impl<'a> Printer<'a> {
438454 }
439455
440456 self . left += 1 ;
441- self . left %= self . buf_len ;
457+ self . left %= self . buf_max_len ;
442458
443459 left_size = self . buf [ self . left ] . size ;
444460 }
0 commit comments