File: oid.go

package info (click to toggle)
golang-github-protonmail-go-crypto 1.1.6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,932 kB
  • sloc: makefile: 10
file content (88 lines) | stat: -rw-r--r-- 2,009 bytes parent folder | download | duplicates (5)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package encoding

import (
	"io"

	"github.com/ProtonMail/go-crypto/openpgp/errors"
)

// OID is used to store a variable-length field with a one-octet size
// prefix. See https://tools.ietf.org/html/rfc6637#section-9.
type OID struct {
	bytes []byte
}

const (
	// maxOID is the maximum number of bytes in a OID.
	maxOID = 254
	// reservedOIDLength1 and reservedOIDLength2 are OID lengths that the RFC
	// specifies are reserved.
	reservedOIDLength1 = 0
	reservedOIDLength2 = 0xff
)

// NewOID returns a OID initialized with bytes.
func NewOID(bytes []byte) *OID {
	switch len(bytes) {
	case reservedOIDLength1, reservedOIDLength2:
		panic("encoding: NewOID argument length is reserved")
	default:
		if len(bytes) > maxOID {
			panic("encoding: NewOID argument too large")
		}
	}

	return &OID{
		bytes: bytes,
	}
}

// Bytes returns the decoded data.
func (o *OID) Bytes() []byte {
	return o.bytes
}

// BitLength is the size in bits of the decoded data.
func (o *OID) BitLength() uint16 {
	return uint16(len(o.bytes) * 8)
}

// EncodedBytes returns the encoded data.
func (o *OID) EncodedBytes() []byte {
	return append([]byte{byte(len(o.bytes))}, o.bytes...)
}

// EncodedLength is the size in bytes of the encoded data.
func (o *OID) EncodedLength() uint16 {
	return uint16(1 + len(o.bytes))
}

// ReadFrom reads into b the next OID from r.
func (o *OID) ReadFrom(r io.Reader) (int64, error) {
	var buf [1]byte
	n, err := io.ReadFull(r, buf[:])
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return int64(n), err
	}

	switch buf[0] {
	case reservedOIDLength1, reservedOIDLength2:
		return int64(n), errors.UnsupportedError("reserved for future extensions")
	}

	o.bytes = make([]byte, buf[0])

	nn, err := io.ReadFull(r, o.bytes)
	if err == io.EOF {
		err = io.ErrUnexpectedEOF
	}

	return int64(n) + int64(nn), err
}