Black Lives Matter. Support the Equal Justice Initiative.

Source file src/index/suffixarray/gen.go

Documentation: index/suffixarray

     1  // Copyright 2019 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  // +build ignore
     7  
     8  // Gen generates sais2.go by duplicating functions in sais.go
     9  // using different input types.
    10  // See the comment at the top of sais.go for details.
    11  package main
    12  
    13  import (
    14  	"bytes"
    15  	"log"
    16  	"os"
    17  	"strings"
    18  )
    19  
    20  func main() {
    21  	log.SetPrefix("gen: ")
    22  	log.SetFlags(0)
    23  
    24  	data, err := os.ReadFile("sais.go")
    25  	if err != nil {
    26  		log.Fatal(err)
    27  	}
    28  
    29  	x := bytes.Index(data, []byte("\n\n"))
    30  	if x < 0 {
    31  		log.Fatal("cannot find blank line after copyright comment")
    32  	}
    33  
    34  	var buf bytes.Buffer
    35  	buf.Write(data[:x])
    36  	buf.WriteString("\n\n// Code generated by go generate; DO NOT EDIT.\n\npackage suffixarray\n")
    37  
    38  	for {
    39  		x := bytes.Index(data, []byte("\nfunc "))
    40  		if x < 0 {
    41  			break
    42  		}
    43  		data = data[x:]
    44  		p := bytes.IndexByte(data, '(')
    45  		if p < 0 {
    46  			p = len(data)
    47  		}
    48  		name := string(data[len("\nfunc "):p])
    49  
    50  		x = bytes.Index(data, []byte("\n}\n"))
    51  		if x < 0 {
    52  			log.Fatalf("cannot find end of func %s", name)
    53  		}
    54  		fn := string(data[:x+len("\n}\n")])
    55  		data = data[x+len("\n}"):]
    56  
    57  		if strings.HasSuffix(name, "_32") {
    58  			buf.WriteString(fix32.Replace(fn))
    59  		}
    60  		if strings.HasSuffix(name, "_8_32") {
    61  			// x_8_32 -> x_8_64 done above
    62  			fn = fix8_32.Replace(stripByteOnly(fn))
    63  			buf.WriteString(fn)
    64  			buf.WriteString(fix32.Replace(fn))
    65  		}
    66  	}
    67  
    68  	if err := os.WriteFile("sais2.go", buf.Bytes(), 0666); err != nil {
    69  		log.Fatal(err)
    70  	}
    71  }
    72  
    73  var fix32 = strings.NewReplacer(
    74  	"32", "64",
    75  	"int32", "int64",
    76  )
    77  
    78  var fix8_32 = strings.NewReplacer(
    79  	"_8_32", "_32",
    80  	"byte", "int32",
    81  )
    82  
    83  func stripByteOnly(s string) string {
    84  	lines := strings.SplitAfter(s, "\n")
    85  	w := 0
    86  	for _, line := range lines {
    87  		if !strings.Contains(line, "256") && !strings.Contains(line, "byte-only") {
    88  			lines[w] = line
    89  			w++
    90  		}
    91  	}
    92  	return strings.Join(lines[:w], "")
    93  }
    94  

View as plain text