-
Notifications
You must be signed in to change notification settings - Fork 181
/
stdio.go
89 lines (78 loc) · 1.76 KB
/
stdio.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Package stdio provide some standard IO util functions.
package stdio
import (
"bufio"
"bytes"
"io"
"os"
"strings"
)
// DiscardReader anything from the reader
func DiscardReader(src io.Reader) {
_, _ = io.Copy(io.Discard, src)
}
// ReadString read contents from io.Reader
func ReadString(r io.Reader) string {
bs, err := io.ReadAll(r)
if err != nil {
return ""
}
return string(bs)
}
// MustReadReader read contents from io.Reader, will panic on error
func MustReadReader(r io.Reader) []byte {
bs, err := io.ReadAll(r)
if err != nil {
panic(err)
}
return bs
}
// NewIOReader instance by input: string, bytes, io.Reader
func NewIOReader(in any) io.Reader {
switch typIn := in.(type) {
case []byte:
return bytes.NewReader(typIn)
case string:
return strings.NewReader(typIn)
case io.Reader:
return typIn
}
panic("invalid input type for create reader")
}
// NewScanner instance by input data or reader
func NewScanner(in any) *bufio.Scanner {
switch typIn := in.(type) {
case io.Reader:
return bufio.NewScanner(typIn)
case []byte:
return bufio.NewScanner(bytes.NewReader(typIn))
case string:
return bufio.NewScanner(strings.NewReader(typIn))
case *bufio.Scanner:
return typIn
default:
panic("invalid input type for create scanner")
}
}
// WriteByte to stdout
func WriteByte(b byte) {
_, _ = os.Stdout.Write([]byte{b})
}
// WriteBytes to stdout
func WriteBytes(bs []byte) {
_, _ = os.Stdout.Write(bs)
}
// WritelnBytes to stdout
func WritelnBytes(bs []byte) {
_, _ = os.Stdout.Write(bs)
_, _ = os.Stdout.Write([]byte("\n"))
}
// WriteString to stdout
func WriteString(s string) {
_, _ = os.Stdout.WriteString(s)
}
// Writeln string to stdout
func Writeln(s string) {
_, _ = os.Stdout.WriteString(s)
_, _ = os.Stdout.Write([]byte("\n"))
}