aboutsummaryrefslogtreecommitdiff
path: root/console/console.go
blob: bbe366efc185762c7b4dc41bf8530c77b42f4eb4 (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
54
55
56
package console

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

type Console struct {
	ich, och chan uint16
	done     chan struct{}
}

func New() *Console {
	c := &Console{
		ich:  make(chan uint16, 1),
		och:  make(chan uint16, 1),
		done: make(chan struct{}),
	}
	go c.read(os.Stdin)
	go c.write(os.Stdout)
	return c
}

func (c *Console) read(r io.Reader) {
	var v uint16
	defer close(c.ich)
	for {
		_, err := fmt.Fscanf(r, "%c", &v)
		if err == io.EOF {
			return
		}
		select {
		case <-c.done:
			return
		case c.ich <- v:
		}
	}
}

func (c *Console) write(w io.Writer) {
	defer close(c.och)
	for {
		select {
		case <-c.done:
			return
		case v := <-c.och:
			fmt.Fprintf(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)) }
func (c *Console) Stop()          { close(c.done) }