From fd774b775e1cd137fd2eb1ddb4400754cb176683 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Mon, 10 May 2021 08:52:15 +0200 Subject: [PATCH] Added Lines (lines of a file represented as a string slice). --- utio/lines.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 utio/lines.go diff --git a/utio/lines.go b/utio/lines.go new file mode 100644 index 0000000..5f3b317 --- /dev/null +++ b/utio/lines.go @@ -0,0 +1,48 @@ +package utio + +import ( + "bufio" + "fmt" + "io" +) + +type Liner struct { + Lines []string +} + +// Lines creates a coder that encodes/decodes the lines of a text file. +func Lines() *Liner { + return &Liner{} +} + +func (l *Liner) Encode(w io.Writer) error { + for _, line := range l.Lines { + if _, err := fmt.Fprintln(w, line); err != nil { + return err + } + } + return nil +} + +func (l *Liner) Decode(r io.Reader) error { + scanner := bufio.NewScanner(r) + for scanner.Scan() { + l.Lines = append(l.Lines, scanner.Text()) + } + return scanner.Err() +} + +// ReadLines reads a text file and splits in lines. +func ReadLines(path string) ([]string, error) { + var l = Lines() + var err = DecodeFile(path, l) + if nil != err { + return nil, err + } + return l.Lines, nil +} + +// WriteLines writes lines to a text file. +func WriteLines(path string, lines []string) error { + return EncodeFile(path, &Liner{lines}) +}