-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcodec.go
More file actions
52 lines (46 loc) · 1.57 KB
/
Copy pathcodec.go
File metadata and controls
52 lines (46 loc) · 1.57 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
// Copyright 2024 The Go Language Server Authors
// SPDX-License-Identifier: BSD-3-Clause
package protocol
import "go.lsp.dev/jsonrpc2"
// lspCodec is the [jsonrpc2.Codec] that marshals LSP message payloads (request
// params and response results) with the generated union-aware [Marshal] and
// [Unmarshal], so sealed-interface union values round-trip correctly over the
// wire. Already-encoded [jsonrpc2.RawMessage] values pass through verbatim,
// matching the jsonrpc2 JSONCodec contract.
//
// It is installed on every connection by [NewServer] and [NewClient] via
// [jsonrpc2.WithCodec].
type lspCodec struct{}
// compile-time check that lspCodec satisfies the Codec contract.
var _ jsonrpc2.Codec = lspCodec{}
// Marshal implements [jsonrpc2.Codec].
func (lspCodec) Marshal(v any) ([]byte, error) {
switch m := v.(type) {
case jsonrpc2.RawMessage:
if m == nil {
return []byte("null"), nil
}
return m, nil
case *jsonrpc2.RawMessage:
if m == nil || *m == nil {
return []byte("null"), nil
}
return *m, nil
}
return Marshal(v)
}
// Unmarshal implements [jsonrpc2.Codec].
//
// Raw messages are copied verbatim, matching the [jsonrpc2.JSONCodec]
// ownership contract. Typed protocol payloads delegate to Unmarshal, whose
// generated byte decoders own one copy of the input and may alias unescaped
// strings and raw JSON value fields into that per-message copy.
func (lspCodec) Unmarshal(data []byte, v any) error {
if p, ok := v.(*jsonrpc2.RawMessage); ok {
b := make(jsonrpc2.RawMessage, len(data))
copy(b, data)
*p = b
return nil
}
return Unmarshal(data, v)
}