Repository navigation
Expand file tree
/
Copy pathbuffer.go
More file actions
67 lines (60 loc) · 1.54 KB
/
Copy pathbuffer.go
File metadata and controls
67 lines (60 loc) · 1.54 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//go:build copilot_inprocess && (darwin || linux || windows)
package ffihost
import (
"io"
"sync"
)
// receiveBuffer is a thread-safe byte buffer that feeds blocking Read from a
// producer thread. The native outbound callback (invoked on a foreign runtime
// thread) appends frames via feed without ever blocking; the JSON-RPC reader
// goroutine drains them via Read, which blocks until data or EOF.
//
// It implements io.ReadCloser so it can be handed to jsonrpc2.NewClient as the
// server → client stream.
type receiveBuffer struct {
mu sync.Mutex
cond *sync.Cond
buf []byte
closed bool
}
func newReceiveBuffer() *receiveBuffer {
rb := &receiveBuffer{}
rb.cond = sync.NewCond(&rb.mu)
return rb
}
func (rb *receiveBuffer) feed(data []byte) {
rb.mu.Lock()
defer rb.mu.Unlock()
if rb.closed {
return
}
rb.buf = append(rb.buf, data...)
rb.cond.Broadcast()
}
// Read blocks until at least one byte is available or the buffer is closed.
// It returns io.EOF only once the buffer is closed and fully drained.
func (rb *receiveBuffer) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
rb.mu.Lock()
defer rb.mu.Unlock()
for len(rb.buf) == 0 && !rb.closed {
rb.cond.Wait()
}
if len(rb.buf) == 0 {
return 0, io.EOF
}
n := copy(p, rb.buf)
rb.buf = rb.buf[n:]
return n, nil
}
// Close marks the buffer closed; subsequent Reads drain remaining bytes then
// return io.EOF. Idempotent.
func (rb *receiveBuffer) Close() error {
rb.mu.Lock()
defer rb.mu.Unlock()
rb.closed = true
rb.cond.Broadcast()
return nil
}