forked from asciinema/asciinema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
53 lines (41 loc) · 990 Bytes
/
stream.go
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
package asciicast
import "time"
type Stream struct {
Frames []Frame
elapsedTime time.Duration
lastWriteTime time.Time
maxWait time.Duration
}
func NewStream(maxWait uint) *Stream {
return &Stream{
lastWriteTime: time.Now(),
maxWait: time.Duration(maxWait) * time.Second,
}
}
func (s *Stream) Write(p []byte) (int, error) {
frame := Frame{}
frame.Delay = s.incrementElapsedTime().Seconds()
frame.Data = make([]byte, len(p))
copy(frame.Data, p)
s.Frames = append(s.Frames, frame)
return len(p), nil
}
func (s *Stream) Close() {
s.incrementElapsedTime()
if string(s.Frames[len(s.Frames)-1].Data) == "exit\r\n" {
s.Frames = s.Frames[:len(s.Frames)-1]
}
}
func (s *Stream) Duration() time.Duration {
return s.elapsedTime
}
func (s *Stream) incrementElapsedTime() time.Duration {
now := time.Now()
d := now.Sub(s.lastWriteTime)
if s.maxWait > 0 && d > s.maxWait {
d = s.maxWait
}
s.elapsedTime += d
s.lastWriteTime = now
return d
}