github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/exp/crc/crc.go (about)

     1  // Copyright 2019 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  // Prints crc checksum of a file.
     6  //
     7  // Synopsis:
     8  //
     9  //	crc OPTIONS [FILE]
    10  //
    11  // Description:
    12  //
    13  //	One of the crc types must be specified. If there is no file, stdin is
    14  //	read.
    15  //
    16  // Options:
    17  //
    18  //	-f: CRC function to use. May be one of the following:
    19  //	    crc32-ieee:       CRC-32 IEEE standard (default)
    20  //	    crc32-castognoli: CRC-32 Castognoli standard
    21  //	    crc32-koopman:    CRC-32 Koopman standard
    22  //	    crc64-ecma:       CRC-64 ECMA standard
    23  //	    crc64-iso:        CRC-64 ISO standard
    24  package main
    25  
    26  import (
    27  	"flag"
    28  	"fmt"
    29  	"hash"
    30  	"hash/crc32"
    31  	"hash/crc64"
    32  	"io"
    33  	"log"
    34  	"os"
    35  )
    36  
    37  var function = flag.String("f", "crc32-ieee", "CRC function")
    38  
    39  func main() {
    40  	flag.Parse()
    41  
    42  	functions := map[string]hash.Hash{
    43  		"crc32-ieee":       crc32.New(crc32.MakeTable(crc32.IEEE)),
    44  		"crc32-castognoli": crc32.New(crc32.MakeTable(crc32.Castagnoli)),
    45  		"crc32-koopman":    crc32.New(crc32.MakeTable(crc32.Koopman)),
    46  		"crc64-ecma":       crc64.New(crc64.MakeTable(crc64.ECMA)),
    47  		"crc64-iso":        crc64.New(crc64.MakeTable(crc64.ISO)),
    48  	}
    49  
    50  	h, ok := functions[*function]
    51  	if !ok {
    52  		expected := ""
    53  		for k := range functions {
    54  			expected += " " + k
    55  		}
    56  		log.Fatalf("invalid function %q, expected one of:%s", *function, expected)
    57  	}
    58  
    59  	var r io.Reader
    60  	switch flag.NArg() {
    61  	case 0:
    62  		r = os.Stdin
    63  	case 1:
    64  		f, err := os.Open(flag.Arg(0))
    65  		if err != nil {
    66  			log.Fatal(err)
    67  		}
    68  		defer f.Close()
    69  		r = f
    70  	default:
    71  		log.Fatal("expected 0 or 1 positional args")
    72  	}
    73  
    74  	if _, err := io.Copy(h, r); err != nil {
    75  		log.Fatal(err)
    76  	}
    77  	fmt.Printf("%x\n", h.Sum([]byte{}))
    78  }