github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/complete/io.go (about)

     1  // Copyright 2012-2018 the u-root 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 complete
     6  
     7  import "strings"
     8  
     9  // InOut is a stack-like interface used for IO.
    10  // We are no longer sure we need it.
    11  type InOut interface {
    12  	// Push one or more strings onto the InOut
    13  	Push(...string)
    14  	// Pop a string fom the InOut.
    15  	Pop() string
    16  	// Pop all strings from the Inout.
    17  	PopAll() []string
    18  	// ReadAll implements io.ReadAll for an InOut.
    19  	ReadAll() ([]byte, error)
    20  	// Write implements io.Write for an InOut
    21  	Write([]byte) (int, error)
    22  }
    23  
    24  // Line is used to implement an InOut based on an array of strings.
    25  type Line struct {
    26  	L []string
    27  }
    28  
    29  // NewLine returns an empty Line struct
    30  func NewLine() InOut {
    31  	return &Line{}
    32  }
    33  
    34  // Push implements Push for a Line
    35  func (l *Line) Push(s ...string) {
    36  	l.L = append(l.L, s...)
    37  }
    38  
    39  // Pop implements Pop for a Line
    40  func (l *Line) Pop() (s string) {
    41  	if len(l.L) == 0 {
    42  		return s
    43  	}
    44  	s, l.L = l.L[len(l.L)-1], l.L[:len(l.L)-1]
    45  	return s
    46  }
    47  
    48  // PopAll implements PopAll for a Line
    49  func (l *Line) PopAll() (s []string) {
    50  	s, l.L = l.L, []string{}
    51  	return
    52  }
    53  
    54  // ReadAll implements ReadAll for a Line. There are no errors.
    55  func (l *Line) ReadAll() ([]byte, error) {
    56  	return []byte(strings.Join(l.PopAll(), "")), nil
    57  }
    58  
    59  // Write implements Write for a Line. There are no errors.
    60  func (l *Line) Write(b []byte) (int, error) {
    61  	l.Push(string(b))
    62  	return len(b), nil
    63  }