Skip to content

Instantly share code, notes, and snippets.

@moriyoshi
Last active March 21, 2018 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moriyoshi/32e71bf5467031f593f8aa501153a714 to your computer and use it in GitHub Desktop.
Save moriyoshi/32e71bf5467031f593f8aa501153a714 to your computer and use it in GitHub Desktop.
import (
"context"
"sync/atomic"
"time"
)
type Contexts struct {
ReaderContext context.Context
ReaderCancel context.CancelFunc
WriterContext context.Context
WriterCancel context.CancelFunc
doneChan chan struct{}
readerDone uintptr
writerDone uintptr
}
func NewContexts(rc context.Context, rcan context.CancelFunc, wc context.Context, wcan context.CancelFunc) *Contexts {
ctxts := &Contexts{
ReaderContext: rc,
ReaderCancel: rcan,
WriterContext: wc,
import (
"context"
"sync/atomic"
"time"
)
type Contexts struct {
ReaderContext context.Context
ReaderCancel context.CancelFunc
WriterContext context.Context
WriterCancel context.CancelFunc
doneChan chan struct{}
readerDone uintptr
writerDone uintptr
}
func NewContexts(rc context.Context, rcan context.CancelFunc, wc context.Context, wcan context.CancelFunc) *Contexts {
ctxts := &Contexts{
ReaderContext: rc,
ReaderCancel: rcan,
WriterContext: wc,
package main
import (
"bufio"
"io"
)
type UndoableScanner struct {
inner *bufio.Scanner
undo [][]byte
next []byte
}
func (s *UndoableScanner) Buffer(buf []byte, max int) {
s.inner.Buffer(buf, max)
}
func (s *UndoableScanner) Bytes() []byte {
if len(s.undo) > 0 {
return s.next
} else {
return s.inner.Bytes()
}
}
func (s *UndoableScanner) Text() string {
return string(s.Bytes())
}
func (s *UndoableScanner) Err() error {
return s.inner.Err()
}
func (s *UndoableScanner) Scan() bool {
if len(s.undo) > 0 {
s.next = s.undo[0]
s.undo = s.undo[1:]
return true
} else {
return s.inner.Scan()
}
}
func (s *UndoableScanner) Undo(b []byte) {
s.undo = append(s.undo, b)
s.next = nil
}
func NewUndoableScanner(r io.Reader, split bufio.SplitFunc) *UndoableScanner {
s := bufio.NewScanner(r)
s.Split(split)
return &UndoableScanner{
inner: s,
undo: make([][]byte, 0, 16),
next: nil,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment