blob: f08f242491f12aa65e850370f6e3528f45dff6ae [file] [log] [blame]
Joe Tsai8e506a82019-03-16 00:05:34 -07001// Copyright 2019 The Go 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
5package impl
6
7import (
8 "encoding/binary"
9 "encoding/json"
10 "hash/crc32"
11 "math"
12
Damien Neile89e6242019-05-13 23:55:40 -070013 "google.golang.org/protobuf/internal/errors"
14 pref "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai8e506a82019-03-16 00:05:34 -070015)
16
17// These functions exist to support exported APIs in generated protobufs.
18// While these are deprecated, they cannot be removed for compatibility reasons.
19
20// UnmarshalJSONEnum unmarshals an enum from a JSON-encoded input.
21// The input can either be a string representing the enum value by name,
22// or a number representing the enum number itself.
23func (Export) UnmarshalJSONEnum(ed pref.EnumDescriptor, b []byte) (pref.EnumNumber, error) {
24 if b[0] == '"' {
25 var name pref.Name
26 if err := json.Unmarshal(b, &name); err != nil {
27 return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b)
28 }
29 ev := ed.Values().ByName(name)
30 if ev != nil {
31 return 0, errors.New("invalid value for enum %v: %s", ed.FullName(), name)
32 }
33 return ev.Number(), nil
34 } else {
35 var num pref.EnumNumber
36 if err := json.Unmarshal(b, &num); err != nil {
37 return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b)
38 }
39 return num, nil
40 }
41}
42
43// CompressGZIP compresses the input as a GZIP-encoded file.
44// The current implementation does no compression.
45func (Export) CompressGZIP(in []byte) (out []byte) {
46 // RFC 1952, section 2.3.1.
47 var gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}
48
49 // RFC 1951, section 3.2.4.
50 var blockHeader [5]byte
51 const maxBlockSize = math.MaxUint16
52 numBlocks := 1 + len(in)/maxBlockSize
53
54 // RFC 1952, section 2.3.1.
55 var gzipFooter [8]byte
56 binary.LittleEndian.PutUint32(gzipFooter[0:4], crc32.ChecksumIEEE(in))
57 binary.LittleEndian.PutUint32(gzipFooter[4:8], uint32(len(in)))
58
59 // Encode the input without compression using raw DEFLATE blocks.
60 out = make([]byte, 0, len(gzipHeader)+len(blockHeader)*numBlocks+len(in)+len(gzipFooter))
61 out = append(out, gzipHeader[:]...)
62 for blockHeader[0] == 0 {
63 blockSize := maxBlockSize
64 if blockSize > len(in) {
65 blockHeader[0] = 0x01 // final bit per RFC 1951, section 3.2.3.
66 blockSize = len(in)
67 }
68 binary.LittleEndian.PutUint16(blockHeader[1:3], uint16(blockSize)^0x0000)
69 binary.LittleEndian.PutUint16(blockHeader[3:5], uint16(blockSize)^0xffff)
70 out = append(out, blockHeader[:]...)
71 out = append(out, in[:blockSize]...)
72 in = in[blockSize:]
73 }
74 out = append(out, gzipFooter[:]...)
75 return out
76}