main
Raw Download raw file
 1// Copyright 2014-2022 Ulrich Kunitz. 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 xz
 6
 7import (
 8	"errors"
 9	"io"
10)
11
12// putUint32LE puts the little-endian representation of x into the first
13// four bytes of p.
14func putUint32LE(p []byte, x uint32) {
15	p[0] = byte(x)
16	p[1] = byte(x >> 8)
17	p[2] = byte(x >> 16)
18	p[3] = byte(x >> 24)
19}
20
21// putUint64LE puts the little-endian representation of x into the first
22// eight bytes of p.
23func putUint64LE(p []byte, x uint64) {
24	p[0] = byte(x)
25	p[1] = byte(x >> 8)
26	p[2] = byte(x >> 16)
27	p[3] = byte(x >> 24)
28	p[4] = byte(x >> 32)
29	p[5] = byte(x >> 40)
30	p[6] = byte(x >> 48)
31	p[7] = byte(x >> 56)
32}
33
34// uint32LE converts a little endian representation to an uint32 value.
35func uint32LE(p []byte) uint32 {
36	return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 |
37		uint32(p[3])<<24
38}
39
40// putUvarint puts a uvarint representation of x into the byte slice.
41func putUvarint(p []byte, x uint64) int {
42	i := 0
43	for x >= 0x80 {
44		p[i] = byte(x) | 0x80
45		x >>= 7
46		i++
47	}
48	p[i] = byte(x)
49	return i + 1
50}
51
52// errOverflow indicates an overflow of the 64-bit unsigned integer.
53var errOverflowU64 = errors.New("xz: uvarint overflows 64-bit unsigned integer")
54
55// readUvarint reads a uvarint from the given byte reader.
56func readUvarint(r io.ByteReader) (x uint64, n int, err error) {
57	const maxUvarintLen = 10
58
59	var s uint
60	i := 0
61	for {
62		b, err := r.ReadByte()
63		if err != nil {
64			return x, i, err
65		}
66		i++
67		if i > maxUvarintLen {
68			return x, i, errOverflowU64
69		}
70		if b < 0x80 {
71			if i == maxUvarintLen && b > 1 {
72				return x, i, errOverflowU64
73			}
74			return x | uint64(b)<<s, i, nil
75		}
76		x |= uint64(b&0x7f) << s
77		s += 7
78	}
79}