go-tg-screenshot-bot
105 строк · 2.6 Кб
1package xgb
2
3/*
4help.go is meant to contain a rough hodge podge of functions that are mainly
5used in the auto generated code. Indeed, several functions here are simple
6wrappers so that the sub-packages don't need to be smart about which stdlib
7packages to import.
8
9Also, the 'Get..' and 'Put..' functions are used through the core xgb package
10too. (xgbutil uses them too.)
11*/
12
13import (
14"fmt"
15"strings"
16)
17
18// StringsJoin is an alias to strings.Join. It allows us to avoid having to
19// import 'strings' in each of the generated Go files.
20func StringsJoin(ss []string, sep string) string {
21return strings.Join(ss, sep)
22}
23
24// Sprintf is so we don't need to import 'fmt' in the generated Go files.
25func Sprintf(format string, v ...interface{}) string {
26return fmt.Sprintf(format, v...)
27}
28
29// Errorf is just a wrapper for fmt.Errorf. Exists for the same reason
30// that 'stringsJoin' and 'sprintf' exists.
31func Errorf(format string, v ...interface{}) error {
32return fmt.Errorf(format, v...)
33}
34
35// Pad a length to align on 4 bytes.
36func Pad(n int) int {
37return (n + 3) & ^3
38}
39
40// PopCount counts the number of bits set in a value list mask.
41func PopCount(mask0 int) int {
42mask := uint32(mask0)
43n := 0
44for i := uint32(0); i < 32; i++ {
45if mask&(1<<i) != 0 {
46n++
47}
48}
49return n
50}
51
52// Put16 takes a 16 bit integer and copies it into a byte slice.
53func Put16(buf []byte, v uint16) {
54buf[0] = byte(v)
55buf[1] = byte(v >> 8)
56}
57
58// Put32 takes a 32 bit integer and copies it into a byte slice.
59func Put32(buf []byte, v uint32) {
60buf[0] = byte(v)
61buf[1] = byte(v >> 8)
62buf[2] = byte(v >> 16)
63buf[3] = byte(v >> 24)
64}
65
66// Put64 takes a 64 bit integer and copies it into a byte slice.
67func Put64(buf []byte, v uint64) {
68buf[0] = byte(v)
69buf[1] = byte(v >> 8)
70buf[2] = byte(v >> 16)
71buf[3] = byte(v >> 24)
72buf[4] = byte(v >> 32)
73buf[5] = byte(v >> 40)
74buf[6] = byte(v >> 48)
75buf[7] = byte(v >> 56)
76}
77
78// Get16 constructs a 16 bit integer from the beginning of a byte slice.
79func Get16(buf []byte) uint16 {
80v := uint16(buf[0])
81v |= uint16(buf[1]) << 8
82return v
83}
84
85// Get32 constructs a 32 bit integer from the beginning of a byte slice.
86func Get32(buf []byte) uint32 {
87v := uint32(buf[0])
88v |= uint32(buf[1]) << 8
89v |= uint32(buf[2]) << 16
90v |= uint32(buf[3]) << 24
91return v
92}
93
94// Get64 constructs a 64 bit integer from the beginning of a byte slice.
95func Get64(buf []byte) uint64 {
96v := uint64(buf[0])
97v |= uint64(buf[1]) << 8
98v |= uint64(buf[2]) << 16
99v |= uint64(buf[3]) << 24
100v |= uint64(buf[4]) << 32
101v |= uint64(buf[5]) << 40
102v |= uint64(buf[6]) << 48
103v |= uint64(buf[7]) << 56
104return v
105}
106