aboutsummaryrefslogtreecommitdiff
path: root/console/console.go
blob: 4fe96808874a6e115a7a6f29c14cab3468408eda (plain)
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
package console

import (
	"context"
	"fmt"
	"io"
	"os"
)

type Console struct {
	r        io.Reader
	w        io.Writer
	ich, och chan uint16
}

func New(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)) }