| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package indented |
| 6 |
| 7 import ( |
| 8 "bytes" |
| 9 "io" |
| 10 ) |
| 11 |
| 12 // Writer inserts indentation before each line. |
| 13 type Writer struct { |
| 14 io.Writer // underlying writer. |
| 15 Level int // number of times \t must be inserted before each line. |
| 16 insideLine bool |
| 17 } |
| 18 |
| 19 var indentation []byte |
| 20 |
| 21 func init() { |
| 22 indentation = make([]byte, 256) |
| 23 for i := range indentation { |
| 24 indentation[i] = '\t' |
| 25 } |
| 26 } |
| 27 |
| 28 // Write writes data inserting a newline before each line. |
| 29 // Panics if w.Indent is outside of [0, 256) range. |
| 30 func (w *Writer) Write(data []byte) (n int, err error) { |
| 31 // Do not print indentation if there is no data. |
| 32 |
| 33 for len(data) > 0 { |
| 34 var printUntil int |
| 35 endsWithNewLine := false |
| 36 |
| 37 lineBeginning := !w.insideLine |
| 38 if data[0] == '\n' && lineBeginning { |
| 39 // This is a blank line. Do not indent it, just print as
is. |
| 40 printUntil = 1 |
| 41 } else { |
| 42 if lineBeginning { |
| 43 // Print indentation. |
| 44 w.Writer.Write(indentation[:w.Level]) |
| 45 w.insideLine = true |
| 46 } |
| 47 |
| 48 lineEnd := bytes.IndexRune(data, '\n') |
| 49 if lineEnd < 0 { |
| 50 // Print the whole thing. |
| 51 printUntil = len(data) |
| 52 } else { |
| 53 // Print until the newline inclusive. |
| 54 printUntil = lineEnd + 1 |
| 55 endsWithNewLine = true |
| 56 } |
| 57 } |
| 58 toPrint := data[:printUntil] |
| 59 data = data[printUntil:] |
| 60 |
| 61 // Assertion: none of the runes in toPrint |
| 62 // can be newline except the last rune. |
| 63 // The last rune is newline iff endsWithNewLine==true. |
| 64 |
| 65 m, err := w.Writer.Write(toPrint) |
| 66 n += m |
| 67 |
| 68 if m == len(toPrint) && endsWithNewLine { |
| 69 // We've printed the newline, so we are the line beginni
ng again. |
| 70 w.insideLine = false |
| 71 } |
| 72 if err != nil { |
| 73 return n, err |
| 74 } |
| 75 } |
| 76 return n, nil |
| 77 } |
| OLD | NEW |