1// Copyright 2017 The Go Authors. 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 5//go:build ignore 6 7// This program generates bits_tables.go. 8 9package main 10 11import ( 12 "bytes" 13 "fmt" 14 "go/format" 15 "io" 16 "log" 17 "os" 18) 19 20var header = []byte(`// Copyright 2017 The Go Authors. All rights reserved. 21// Use of this source code is governed by a BSD-style 22// license that can be found in the LICENSE file. 23 24// Code generated by go run make_tables.go. DO NOT EDIT. 25 26package bits 27 28`) 29 30func main() { 31 buf := bytes.NewBuffer(header) 32 33 gen(buf, "ntz8tab", ntz8) 34 gen(buf, "pop8tab", pop8) 35 gen(buf, "rev8tab", rev8) 36 gen(buf, "len8tab", len8) 37 38 out, err := format.Source(buf.Bytes()) 39 if err != nil { 40 log.Fatal(err) 41 } 42 43 err = os.WriteFile("bits_tables.go", out, 0666) 44 if err != nil { 45 log.Fatal(err) 46 } 47} 48 49func gen(w io.Writer, name string, f func(uint8) uint8) { 50 // Use a const string to allow the compiler to constant-evaluate lookups at constant index. 51 fmt.Fprintf(w, "const %s = \"\"+\n\"", name) 52 for i := 0; i < 256; i++ { 53 fmt.Fprintf(w, "\\x%02x", f(uint8(i))) 54 if i%16 == 15 && i != 255 { 55 fmt.Fprint(w, "\"+\n\"") 56 } 57 } 58 fmt.Fprint(w, "\"\n\n") 59} 60 61func ntz8(x uint8) (n uint8) { 62 for x&1 == 0 && n < 8 { 63 x >>= 1 64 n++ 65 } 66 return 67} 68 69func pop8(x uint8) (n uint8) { 70 for x != 0 { 71 x &= x - 1 72 n++ 73 } 74 return 75} 76 77func rev8(x uint8) (r uint8) { 78 for i := 8; i > 0; i-- { 79 r = r<<1 | x&1 80 x >>= 1 81 } 82 return 83} 84 85func len8(x uint8) (n uint8) { 86 for x != 0 { 87 x >>= 1 88 n++ 89 } 90 return 91} 92