File: gen.go

package info (click to toggle)
golang-github-cloudflare-circl 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,064 kB
  • sloc: asm: 20,492; ansic: 1,292; makefile: 68
file content (97 lines) | stat: -rw-r--r-- 1,809 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//go:build ignore
// +build ignore

// Autogenerates wrappers from templates to prevent too much duplicated code
// between the code for different modes.
package main

import (
	"bytes"
	"fmt"
	"go/format"
	"io/ioutil"
	"path"
	"strings"
	"text/template"
)

type Instance struct {
	Name string
}

func (m Instance) KemName() string {
	if m.NIST() {
		return m.Name
	}
	return m.Name + ".CCAKEM"
}

func (m Instance) NIST() bool {
	return strings.HasPrefix(m.Name, "ML-KEM")
}

func (m Instance) PkePkg() string {
	if !m.NIST() {
		return m.Pkg()
	}
	return strings.ReplaceAll(m.Pkg(), "mlkem", "kyber")
}

func (m Instance) Pkg() string {
	return strings.ToLower(strings.ReplaceAll(m.Name, "-", ""))
}

func (m Instance) PkgPath() string {
	if m.NIST() {
		return path.Join("..", "mlkem", m.Pkg())
	}
	return m.Pkg()
}

var (
	Instances = []Instance{
		{Name: "Kyber512"},
		{Name: "Kyber768"},
		{Name: "Kyber1024"},
		{Name: "ML-KEM-512"},
		{Name: "ML-KEM-768"},
		{Name: "ML-KEM-1024"},
	}
	TemplateWarning = "// Code generated from"
)

func main() {
	generatePackageFiles()
}

// Generates instance/kyber.go from templates/pkg.templ.go
func generatePackageFiles() {
	tl, err := template.ParseFiles("templates/pkg.templ.go")
	if err != nil {
		panic(err)
	}

	for _, mode := range Instances {
		buf := new(bytes.Buffer)
		err := tl.Execute(buf, mode)
		if err != nil {
			panic(err)
		}

		// Formating output code
		code, err := format.Source(buf.Bytes())
		if err != nil {
			panic(fmt.Sprintf("error formating code: %v", err))
		}

		res := string(code)
		offset := strings.Index(res, TemplateWarning)
		if offset == -1 {
			panic("Missing template warning in pkg.templ.go")
		}
		err = ioutil.WriteFile(mode.PkgPath()+"/kyber.go", []byte(res[offset:]), 0o644)
		if err != nil {
			panic(err)
		}
	}
}