start state machine parser

This commit is contained in:
dre 2021-07-03 23:58:03 +08:00
parent 57896f7dcd
commit d5b609b6ea
2 changed files with 49 additions and 8 deletions

View file

@ -53,14 +53,7 @@ func write(out string, data <-chan []byte, quit chan struct{}) error {
NewParser(data, w, quit).Parse()
for {
select {
case <-quit:
return nil
case b := <-data:
fmt.Fprintf(w, string(b)+"\n")
}
}
return nil
}
func main() {

48
parser.go Normal file
View file

@ -0,0 +1,48 @@
package main
import (
"fmt"
"io"
)
// state function
type stateFn func(*fsm, []byte) stateFn
// state machine
type fsm struct {
state stateFn
out io.Writer
quit chan struct{}
data <-chan []byte
}
func NewParser(data <-chan []byte, writer io.Writer, quit chan struct{}) *fsm {
return &fsm{
out: writer,
data: data,
quit: quit,
}
}
func (m *fsm) Parse() {
var buffer []byte
for m.state = initial; m.state != nil; {
select {
case <-m.quit:
m.state = nil
case buffer = <-m.data:
m.state = m.state(m, buffer)
}
}
}
func initial(m *fsm, data []byte) stateFn {
// TODO
// find linebreaks
// find code fences
// find links
// collapse lists
fmt.Fprintf(m.out, string(data)+"\n")
return initial
}