You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
1.6 KiB
Go

10 years ago
package main
import (
"bufio"
"bytes"
"fmt"
"io"
)
type statement struct {
head *node
tail *node
}
func (s statement) String() string {
var buf bytes.Buffer
s.each(func(n *node) error {
10 years ago
_, err := fmt.Fprint(&buf, n)
return err
10 years ago
})
return buf.String()
}
func (s *statement) each(fn func(*node) error) error {
curr := s.head
for curr != nil {
10 years ago
err := fn(curr)
if err != nil {
return err
}
10 years ago
curr = curr.next
}
10 years ago
return nil
10 years ago
}
func (s *statement) write(w io.Writer) error {
10 years ago
return s.each(func(n *node) error {
_, err := w.Write(n.line)
return err
})
10 years ago
}
type node struct {
line []byte
next *node
}
func (n node) String() string {
return fmt.Sprintf("%s", n.line)
}
func (s *statement) add(line []byte) {
n := &node{line, nil}
if s.head == nil {
s.head = n
} else if s.head.next == nil {
10 years ago
s.head.next = n
}
10 years ago
if s.tail != nil {
s.tail.next = n
}
10 years ago
s.tail = n
10 years ago
}
func whitespace(buf []byte) bool {
10 years ago
for i, _ := range buf {
switch buf[i] {
case '\r', '\n':
default:
return false
}
}
return true
10 years ago
}
func split(r io.Reader, c chan statement) {
defer close(c)
br := bufio.NewReader(r)
var s *statement
for {
line, err := br.ReadBytes('\n')
switch err {
case nil:
case io.EOF:
10 years ago
if s != nil {
c <- *s
}
10 years ago
return
default:
fmt.Printf("error on read: %v\n", err)
return
}
10 years ago
if whitespace(line) {
continue
}
10 years ago
if line[len(line)-2] != '\r' {
fmt.Printf("bad line terminator")
break
}
if line[0] == '*' {
10 years ago
if s != nil {
c <- *s
}
s = new(statement)
s.add(line)
10 years ago
} else {
if s == nil {
fmt.Println("ummm wut")
return
}
s.add(line)
}
}
}