make_tables.go 1.6 KB

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