github.com/F4RD1N/gomobile@v1.0.1/bind/printer.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package bind
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  )
    11  
    12  type Printer struct {
    13  	Buf        *bytes.Buffer
    14  	IndentEach []byte
    15  	indentText []byte
    16  	needIndent bool
    17  }
    18  
    19  func (p *Printer) writeIndent() error {
    20  	if !p.needIndent {
    21  		return nil
    22  	}
    23  	p.needIndent = false
    24  	_, err := p.Buf.Write(p.indentText)
    25  	return err
    26  }
    27  
    28  func (p *Printer) Write(b []byte) (n int, err error) {
    29  	wrote := 0
    30  	for len(b) > 0 {
    31  		if err := p.writeIndent(); err != nil {
    32  			return wrote, err
    33  		}
    34  		i := bytes.IndexByte(b, '\n')
    35  		if i < 0 {
    36  			break
    37  		}
    38  		n, err = p.Buf.Write(b[0 : i+1])
    39  		wrote += n
    40  		if err != nil {
    41  			return wrote, err
    42  		}
    43  		b = b[i+1:]
    44  		p.needIndent = true
    45  	}
    46  	if len(b) > 0 {
    47  		n, err = p.Buf.Write(b)
    48  		wrote += n
    49  	}
    50  	return wrote, err
    51  }
    52  
    53  func (p *Printer) Printf(format string, args ...interface{}) {
    54  	if _, err := fmt.Fprintf(p, format, args...); err != nil {
    55  		panic(fmt.Sprintf("printer: %v", err))
    56  	}
    57  }
    58  
    59  func (p *Printer) Indent() {
    60  	p.indentText = append(p.indentText, p.IndentEach...)
    61  }
    62  
    63  func (p *Printer) Outdent() {
    64  	if len(p.indentText) > len(p.IndentEach)-1 {
    65  		p.indentText = p.indentText[len(p.IndentEach):]
    66  	}
    67  }