File: binary.go

package info (click to toggle)
golang-bugst-relaxed-semver 0.15.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 260 kB
  • sloc: makefile: 2
file content (90 lines) | stat: -rw-r--r-- 2,441 bytes parent folder | download
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
89
90
//
// Copyright 2018-2025 Cristian Maglie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//

package semver

import (
	"bytes"
	"encoding/binary"
)

func marshalByteArray(b []byte) []byte {
	l := len(b)
	res := make([]byte, l+4)
	binary.BigEndian.PutUint32(res, uint32(l))
	copy(res[4:], b)
	return res
}

// MarshalBinary implements binary custom encoding
func (v *Version) MarshalBinary() ([]byte, error) {
	// TODO could be preallocated without bytes.Buffer
	res := new(bytes.Buffer)
	intBuff := [4]byte{}
	_, _ = res.Write(marshalByteArray([]byte(v.raw)))
	binary.BigEndian.PutUint32(intBuff[:], uint32(v.major))
	_, _ = res.Write(intBuff[:])
	binary.BigEndian.PutUint32(intBuff[:], uint32(v.minor))
	_, _ = res.Write(intBuff[:])
	binary.BigEndian.PutUint32(intBuff[:], uint32(v.patch))
	_, _ = res.Write(intBuff[:])
	binary.BigEndian.PutUint32(intBuff[:], uint32(v.prerelease))
	_, _ = res.Write(intBuff[:])
	binary.BigEndian.PutUint32(intBuff[:], uint32(v.build))
	_, _ = res.Write(intBuff[:])
	return res.Bytes(), nil
}

func decodeArray(data []byte) ([]byte, []byte) {
	l, data := int(binary.BigEndian.Uint32(data)), data[4:]
	return data[:l], data[l:]
}

func decodeInt(data []byte) (int, []byte) {
	return int(binary.BigEndian.Uint32(data)), data[4:]
}

// UnmarshalJSON implements binary custom decoding
func (v *Version) UnmarshalBinary(data []byte) error {
	var buff []byte

	buff, data = decodeArray(data)
	v.raw = string(buff)
	v.bytes = []byte(v.raw)
	v.major, data = decodeInt(data)
	v.minor, data = decodeInt(data)
	v.patch, data = decodeInt(data)
	v.prerelease, data = decodeInt(data)
	v.build, _ = decodeInt(data)
	return nil
}

// MarshalBinary implements encoding.BinaryMarshaler
func (v *RelaxedVersion) MarshalBinary() ([]byte, error) {
	res := new(bytes.Buffer)
	if len(v.customversion) > 0 {
		_, _ = res.Write([]byte{0})
		_, _ = res.Write(marshalByteArray(v.customversion))
		return res.Bytes(), nil
	}
	res.Write([]byte{1})
	d, _ := v.version.MarshalBinary() // can't fail
	_, _ = res.Write(d)
	return res.Bytes(), nil
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler
func (v *RelaxedVersion) UnmarshalBinary(data []byte) error {
	if data[0] == 0 {
		v.customversion, _ = decodeArray(data[1:])
		v.version = nil
		return nil
	}

	v.customversion = nil
	v.version = &Version{}
	return v.version.UnmarshalBinary(data[1:])
}