diff options
author | Dimitri Sokolyuk <demon@dim13.org> | 2018-01-15 00:06:40 +0100 |
---|---|---|
committer | Dimitri Sokolyuk <demon@dim13.org> | 2018-01-15 00:06:40 +0100 |
commit | 4f07f821e0d04e0cb6ec62d1d5bc3999dd7ba89a (patch) | |
tree | 27b6e1124b247769b6650544f19cdd925285bd80 /console.go | |
parent | 8a566444c4e3e75977bbb1629891b3fe594c3069 (diff) |
use context for cancelation
Diffstat (limited to 'console.go')
-rw-r--r-- | console.go | 56 |
1 files changed, 51 insertions, 5 deletions
@@ -1,15 +1,61 @@ package j1 import ( + "context" + "fmt" "io" "os" ) -type Console struct { - io.Reader - io.Writer +type console struct { + r io.Reader + w io.Writer + ich, och chan uint16 } -func NewConsole() *Console { - return &Console{Reader: os.Stdin, Writer: os.Stdout} +func NewConsole(ctx context.Context) *console { + c := &console{ + r: os.Stdin, + w: os.Stdout, + ich: make(chan uint16, 1), + och: make(chan uint16, 1), + } + go c.read(ctx) + go c.write(ctx) + return c +} + +func (c *console) read(ctx context.Context) { + var v uint16 + for { + fmt.Fscanf(c.r, "%c", &v) + select { + case <-ctx.Done(): + return + case c.ich <- v: + } + } +} + +func (c *console) write(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case v := <-c.och: + fmt.Fprintf(c.w, "%c", v) + } + } +} + +func (c *console) Read() uint16 { + return <-c.ich +} + +func (c *console) Write(v uint16) { + c.och <- v +} + +func (c *console) Len() uint16 { + return uint16(len(c.ich)) } |