From 54a9f10120506becefbfb2bede3d651ceac70ed5 Mon Sep 17 00:00:00 2001 From: jienfak Date: Mon, 23 Mar 2020 21:12:50 +0500 Subject: [PATCH] input: Standardized input module added. --- input/read.go | 39 +++++++++++++++++++++++++++++++++++++++ sort/sort.go | 20 +++----------------- yes/yes.go | 7 +++---- 3 files changed, 45 insertions(+), 21 deletions(-) create mode 100644 input/read.go diff --git a/input/read.go b/input/read.go new file mode 100644 index 0000000..a9c961d --- /dev/null +++ b/input/read.go @@ -0,0 +1,39 @@ +package input + +import ( + "os" + "io" + "bufio" +) + +func ReadAllRaw(f *os.File) ([]byte, error) { + ret := make([]byte, 0) + b := make([]byte, 512) + for { + n, e := f.Read(b) + if n>0 { + ret = append(ret, b[:n]...) + } + if e == io.EOF { + break + }else if e != nil { + return nil, e + } + } + return ret, nil +} + +func ReadAllLines(f *os.File)( []string, error ){ + r := bufio.NewReader(f) + a := make([]string, 0) + for { + l, e := r.ReadString('\n') + if e==io.EOF { + break + }else if e != nil { + return nil, e + } + a = append(a, l) + } + return a, nil +} diff --git a/sort/sort.go b/sort/sort.go index 02f5b76..3fa3620 100644 --- a/sort/sort.go +++ b/sort/sort.go @@ -1,37 +1,23 @@ package sort import ( - "bufio" "fmt" "os" "sort" - "io" "flag" + "github.com/jienfak/goblin/input" ) -func ReadLines() []string { - - r := bufio.NewReader(os.Stdin) - a := make([]string, 0) - for { - l, e := r.ReadString('\n') - if e==io.EOF { - break - } - a = append(a, l) - } - return a -} - func Run(args []string) int { flagSet := flag.NewFlagSet(args[0], flag.ExitOnError) flagSet.Parse(args[1:]) status := 0 - lines := ReadLines() + lines, _ := input.ReadAllLines(os.Stdin) sort.Strings(lines) for _, l := range lines { fmt.Print(l) } + return status } diff --git a/yes/yes.go b/yes/yes.go index 5bb827f..caa9af1 100644 --- a/yes/yes.go +++ b/yes/yes.go @@ -6,7 +6,7 @@ import( "fmt" "flag" "strings" - "github.com/jienfak/goblin/sort" + "github.com/jienfak/goblin/input" ) func yes(s string){ @@ -30,14 +30,13 @@ func Run(args []string) int { flagSet.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s: %s [options] [string]\n", arg0, arg0) flagSet.PrintDefaults() - } flagSet.Parse(args) args = flagSet.Args() if stdinFlag { - in := sort.ReadLines() - s = strings.Join(in, "") + in, _ := input.ReadAllRaw(os.Stdin) + s = string(in) } else { if len(args)>0 { s = strings.Join(args, " ")