1+ //go:build !goexperiment.jsonv2
2+
13/* Copyright 2016-2017 Vector Creations Ltd
24 *
35 * Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,16 +19,32 @@ package canonicaljson
1719
1820import (
1921 "encoding/binary"
22+ "encoding/json"
2023 "fmt"
2124 "sort"
2225 "unicode/utf8"
2326
2427 "github.com/tidwall/gjson"
2528)
2629
30+ func Canonicalize (input * json.RawMessage ) error {
31+ * input = CanonicalJSONAssumeValid (* input )
32+ return nil
33+ }
34+
35+ func Marshal (v any ) (json.RawMessage , error ) {
36+ marshaled , err := json .Marshal (v )
37+ if err != nil {
38+ return nil , err
39+ }
40+ return CanonicalJSONAssumeValid (marshaled ), nil
41+ }
42+
2743// CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is
2844// the shortest possible encoding using integer values with sorted object keys.
2945// https://matrix.org/docs/spec/appendices#canonical-json
46+ //
47+ // Deprecated: Use the new Canonicalize or Marshal functions which will transparently migrate to jsonv2
3048func CanonicalJSON (input []byte ) ([]byte , error ) {
3149 if ! gjson .Valid (string (input )) {
3250 return nil , fmt .Errorf ("invalid json" )
@@ -37,13 +55,17 @@ func CanonicalJSON(input []byte) ([]byte, error) {
3755
3856// CanonicalJSONAssumeValid is the same as CanonicalJSON, but assumes the
3957// input is valid JSON
58+ //
59+ // Deprecated: Use the new Canonicalize or Marshal functions which will transparently migrate to jsonv2
4060func CanonicalJSONAssumeValid (input []byte ) []byte {
4161 input = CompactJSON (input , make ([]byte , 0 , len (input )))
4262 return SortJSON (input , make ([]byte , 0 , len (input )))
4363}
4464
4565// SortJSON reencodes the JSON with the object keys sorted by lexicographically
4666// by codepoint. The input must be valid JSON.
67+ //
68+ // Deprecated: Use the new Canonicalize or Marshal functions which will transparently migrate to jsonv2
4769func SortJSON (input , output []byte ) []byte {
4870 result := gjson .ParseBytes (input )
4971
@@ -141,6 +163,8 @@ func sortJSONObject(input gjson.Result, inputJSON, output []byte) []byte {
141163
142164// CompactJSON makes the encoded JSON as small as possible by removing
143165// whitespace and unneeded unicode escapes
166+ //
167+ // Deprecated: Use the new Canonicalize or Marshal functions which will transparently migrate to jsonv2
144168func CompactJSON (input , output []byte ) []byte {
145169 var i int
146170 for i < len (input ) {
0 commit comments