github.com/cloudflare/circl@v1.5.0/kem/kyber/gen.go (about) 1 //go:build ignore 2 // +build ignore 3 4 // Autogenerates wrappers from templates to prevent too much duplicated code 5 // between the code for different modes. 6 package main 7 8 import ( 9 "bytes" 10 "fmt" 11 "go/format" 12 "io/ioutil" 13 "path" 14 "strings" 15 "text/template" 16 ) 17 18 type Instance struct { 19 Name string 20 } 21 22 func (m Instance) KemName() string { 23 if m.NIST() { 24 return m.Name 25 } 26 return m.Name + ".CCAKEM" 27 } 28 29 func (m Instance) NIST() bool { 30 return strings.HasPrefix(m.Name, "ML-KEM") 31 } 32 33 func (m Instance) PkePkg() string { 34 if !m.NIST() { 35 return m.Pkg() 36 } 37 return strings.ReplaceAll(m.Pkg(), "mlkem", "kyber") 38 } 39 40 func (m Instance) Pkg() string { 41 return strings.ToLower(strings.ReplaceAll(m.Name, "-", "")) 42 } 43 44 func (m Instance) PkgPath() string { 45 if m.NIST() { 46 return path.Join("..", "mlkem", m.Pkg()) 47 } 48 return m.Pkg() 49 } 50 51 var ( 52 Instances = []Instance{ 53 {Name: "Kyber512"}, 54 {Name: "Kyber768"}, 55 {Name: "Kyber1024"}, 56 {Name: "ML-KEM-512"}, 57 {Name: "ML-KEM-768"}, 58 {Name: "ML-KEM-1024"}, 59 } 60 TemplateWarning = "// Code generated from" 61 ) 62 63 func main() { 64 generatePackageFiles() 65 } 66 67 // Generates instance/kyber.go from templates/pkg.templ.go 68 func generatePackageFiles() { 69 tl, err := template.ParseFiles("templates/pkg.templ.go") 70 if err != nil { 71 panic(err) 72 } 73 74 for _, mode := range Instances { 75 buf := new(bytes.Buffer) 76 err := tl.Execute(buf, mode) 77 if err != nil { 78 panic(err) 79 } 80 81 // Formating output code 82 code, err := format.Source(buf.Bytes()) 83 if err != nil { 84 panic(fmt.Sprintf("error formating code: %v", err)) 85 } 86 87 res := string(code) 88 offset := strings.Index(res, TemplateWarning) 89 if offset == -1 { 90 panic("Missing template warning in pkg.templ.go") 91 } 92 err = ioutil.WriteFile(mode.PkgPath()+"/kyber.go", []byte(res[offset:]), 0o644) 93 if err != nil { 94 panic(err) 95 } 96 } 97 }