github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/exp/cksum/cksum.go (about) 1 // Copyright 2018 the u-root 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 package main 6 7 import ( 8 "fmt" 9 "hash/crc32" 10 "io/ioutil" 11 "os" 12 13 "github.com/spf13/pflag" 14 ) 15 16 func reverse(x uint32) uint32 { 17 x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)) 18 x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)) 19 x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)) 20 x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)) 21 return ((x >> 16) | (x << 16)) 22 } 23 24 func reverseByte(b byte) byte { 25 b = (b&0xF0)>>4 | (b&0x0F)<<4 26 b = (b&0xCC)>>2 | (b&0x33)<<2 27 b = (b&0xAA)>>1 | (b&0x55)<<1 28 return b 29 } 30 31 func reverseBytes(b []byte) []byte { 32 for i := range b { 33 b[i] = reverseByte(b[i]) 34 } 35 return b 36 } 37 38 func helpPrinter() { 39 fmt.Printf("Usage:\ncksum <File Name>\n") 40 pflag.PrintDefaults() 41 os.Exit(0) 42 } 43 44 func versionPrinter() { 45 fmt.Println("cksum utility, URoot Version.") 46 os.Exit(0) 47 } 48 49 func getInput(fileName string) (input []byte, err error) { 50 if fileName != "" { 51 return ioutil.ReadFile(fileName) 52 } 53 return ioutil.ReadAll(os.Stdin) 54 } 55 56 func appendLengthToData(data []byte) []byte { 57 length := len(data) 58 for length > 0 { 59 data = append(data, byte(length)) 60 length = (length >> 8) 61 } 62 return data 63 } 64 65 func calculateCksum(data []byte) uint32 { 66 return reverse(crc32.Update(0xffffffff, crc32.MakeTable(0xEDB88320), reverseBytes(appendLengthToData(data)))) 67 } 68 69 func main() { 70 var ( 71 help bool 72 version bool 73 ) 74 cliArgs := "" 75 pflag.BoolVarP(&help, "help", "h", false, "Show this help and exit") 76 pflag.BoolVarP(&version, "version", "v", false, "Print Version") 77 pflag.Parse() 78 79 if help { 80 helpPrinter() 81 } 82 83 if version { 84 versionPrinter() 85 } 86 if len(os.Args) >= 2 { 87 cliArgs = os.Args[1] 88 } 89 input, err := getInput(cliArgs) 90 if err != nil { 91 return 92 } 93 fmt.Println(calculateCksum(input), len(input), cliArgs) 94 }