Skip to content

Commit c675c6a

Browse files
committed
stream: add stream.go
1 parent 10a438b commit c675c6a

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

stream.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Copyright 2019 The go-language-server Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
package jsonrpc2
6+
7+
import (
8+
"context"
9+
"io"
10+
"sync"
11+
12+
"github.com/francoispqt/gojay"
13+
)
14+
15+
// Stream abstracts the transport mechanics from the JSON RPC protocol.
16+
type Stream interface {
17+
// Read gets the next message from the stream.
18+
Read(context.Context) ([]byte, error)
19+
// Write sends a message to the stream.
20+
Write(context.Context, []byte) error
21+
}
22+
23+
func NewStream(in io.Reader, out io.Writer) Stream {
24+
return &stream{
25+
in: gojay.BorrowDecoder(in),
26+
out: out,
27+
}
28+
}
29+
30+
type stream struct {
31+
in *gojay.Decoder
32+
sync.Mutex
33+
out io.Writer
34+
}
35+
36+
func (s *stream) Read(ctx context.Context) ([]byte, error) {
37+
select {
38+
case <-ctx.Done():
39+
return nil, ctx.Err()
40+
default:
41+
}
42+
43+
defer s.in.Release()
44+
45+
var data []byte
46+
if err := s.in.Decode(&data); err != nil {
47+
return nil, err
48+
}
49+
50+
return data, nil
51+
}
52+
53+
func (s *stream) Write(ctx context.Context, data []byte) error {
54+
select {
55+
case <-ctx.Done():
56+
return ctx.Err()
57+
default:
58+
}
59+
s.Lock()
60+
_, err := s.out.Write(data)
61+
s.Unlock()
62+
63+
return err
64+
}

0 commit comments

Comments
 (0)