github.com/kubiko/snapd@v0.0.0-20201013125620-d4f3094d9ddf/strutil/chrorder/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"regexp"
     8  )
     9  
    10  var (
    11  	matchDigit = regexp.MustCompile("[0-9]").Match
    12  	matchAlpha = regexp.MustCompile("[a-zA-Z]").Match
    13  )
    14  
    15  func chOrder(ch uint8) int {
    16  	// "~" is lower than everything else
    17  	if ch == '~' {
    18  		return -10
    19  	}
    20  	// empty is higher than "~" but lower than everything else
    21  	if ch == 0 {
    22  		return -5
    23  	}
    24  	if matchAlpha([]byte{ch}) {
    25  		return int(ch)
    26  	}
    27  
    28  	// can only happen if cmpString sets '0' because there is no fragment
    29  	if matchDigit([]byte{ch}) {
    30  		return 0
    31  	}
    32  
    33  	return int(ch) + 256
    34  }
    35  
    36  func main() {
    37  	var outFile string
    38  	var pkgName string
    39  	flag.StringVar(&outFile, "output", "-", "output file")
    40  	flag.StringVar(&pkgName, "package", "foo", "package name")
    41  	flag.Parse()
    42  
    43  	out := os.Stdout
    44  	if outFile != "" && outFile != "-" {
    45  		var err error
    46  		out, err = os.Create(outFile)
    47  		if err != nil {
    48  			fmt.Fprintf(os.Stderr, "error: %v", err)
    49  			os.Exit(1)
    50  		}
    51  		defer out.Close()
    52  	}
    53  
    54  	if pkgName == "" {
    55  		pkgName = "foo"
    56  	}
    57  
    58  	fmt.Fprintln(out, "// auto-generated, DO NOT EDIT!")
    59  	fmt.Fprintf(out, "package %v\n", pkgName)
    60  	fmt.Fprintf(out, "\n")
    61  	fmt.Fprintln(out, "var chOrder = [...]int{")
    62  	for i := 0; i < 16; i++ {
    63  		fmt.Fprintf(out, "\t")
    64  		for j := 0; j < 16; j++ {
    65  			if j != 0 {
    66  				fmt.Fprintf(out, " ")
    67  			}
    68  			fmt.Fprintf(out, "%d,", chOrder(uint8(i*16+j)))
    69  
    70  		}
    71  		fmt.Fprintf(out, "\n")
    72  	}
    73  	fmt.Fprintln(out, "}")
    74  }