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