Debian Codegraph @

token/p11token/byteorder.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 package p11token
18
19 import (
20 "encoding/binary"
21 "fmt"
22 "unsafe"
23 )
24
25 var (
26 nativeOrder binary.ByteOrder
27 ulongSize int
28 )
29
30 func init() {
31 var i uint32 = 0x1
32 bs := (*[4]byte)(unsafe.Pointer(&i))
33 if bs[0] == 0 {
34 nativeOrder = binary.BigEndian
35 } else {
36 nativeOrder = binary.LittleEndian
37 }
38 var j uint
39 ulongSize = int(unsafe.Sizeof(j))
40 }
41
42 func putUlong(buf []byte, v uint) {
43 switch ulongSize {
44 case 4:
45 nativeOrder.PutUint32(buf, uint32(v))
46 case 8:
47 nativeOrder.PutUint64(buf, uint64(v))
48 default:
49 panic("can't determine native integer size")
50 }
51 }
52
53 func getUlong(value []byte) (uint, error) {
54 switch len(value) {
55 case 8:
56 return uint(nativeOrder.Uint64(value)), nil
57 case 4:
58 return uint(nativeOrder.Uint32(value)), nil
59 case 2:
60 return uint(nativeOrder.Uint16(value)), nil
61 case 1:
62 return uint(value[0]), nil
63 }
64 return 0, IntegerError{Raw: value}
65 }
66
67 type IntegerError struct {
68 Raw []byte
69 }
70
71 func (e IntegerError) Error() string {
72 return fmt.Sprintf("unable to parse value as unsigned integer: %x", e.Raw)
73 }