golangリングバッファReader Wirter Circle Buffer
package main
import (
"errors"
"fmt"
"io"
"time"
)
type CircleByteBuffer struct {
io.Reader
io.Writer
io.Closer
datas []byte
start int
end int
size int
isClose bool
isEnd bool
}
func NewCircleByteBuffer(len int)*CircleByteBuffer{
var e=new(CircleByteBuffer)
e.datas=make([]byte,len)
e.start=0
e.end=0
e.size=len
e.isClose=false
e.isEnd=false
return e
}
func (e*CircleByteBuffer)getLen()int{
if e.start==e.end{
return 0
}else if e.start=e.getLen() {
panic("out buffer")
}
var pos=e.start+i
if pos>=e.size {
pos -= e.size
}
return e.datas[pos]
}
/*func (e*CircleByteBuffer)puts(bts []byte){
for i:=0;i
二重スレッドセキュリティ、例:
func main() {
fmt.Println("hello world")
b:=NewCircleByteBuffer(1024)
go func(){
for i:=0;i<10;i++ {
bts:=[]byte{byte(i)}
b.Write(bts)
time.Sleep(time.Second)
}
fmt.Println("Close!")
b.Close()
}()
buf:=make([]byte,512)
for{
n,err:=b.Read(buf)
if n>0{
fmt.Println("Reads:",buf[0:n])
}
if err!=nil{
break
}
}
fmt.Println("end!")
}
出力:
hello world
Reads: [0]
Reads: [1]
Reads: [2]
Reads: [3]
Reads: [4]
Reads: [5]
Reads: [6]
Reads: [7]
Reads: [8]
Reads: [9]
Close!
end!