aboutsummaryrefslogtreecommitdiff
path: root/console/console.go
blob: 577e0216b9006ef4c652e10ba996cd70d9b36d23 (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
package console

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

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

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

func (c *Console) read() {
	var v uint16
	for {
		fmt.Fscanf(c.r, "%c", &v)
		select {
		case <-c.done:
			return
		case c.ich <- v:
		}
	}
}

func (c *Console) write() {
	for {
		select {
		case <-c.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)) }
func (c *Console) Stop()          { close(c.done) }