github.com/consensys/gnark-crypto@v0.14.0/field/generator/internal/templates/element/fixed_exp.go (about)

     1  package element
     2  
     3  const FixedExp = `
     4  
     5  {{- if .SqrtQ3Mod4}}
     6  	{{expByAddChain "SqrtExp" .SqrtQ3Mod4ExponentData .ElementName}}
     7  {{- else if .SqrtAtkin}}
     8  	{{expByAddChain "SqrtExp" .SqrtAtkinExponentData .ElementName}}
     9  {{- else if .SqrtTonelliShanks}}
    10  	{{expByAddChain "SqrtExp" .SqrtSMinusOneOver2Data .ElementName}}
    11  {{- end }}
    12  
    13  {{expByAddChain "LegendreExp" .LegendreExponentData .ElementName}}
    14  
    15  
    16  {{define "expByAddChain name data eName"}}
    17  	
    18  // expBy{{.name}} is equivalent to z.Exp(x, {{ .data.N }})
    19  // 
    20  // uses {{ .data.Meta.Module }} {{ .data.Meta.ReleaseTag }} to generate a shorter addition chain
    21  func (z *{{.eName}}) expBy{{$.name}}(x {{.eName}}) *{{.eName}} {
    22  	// addition chain:
    23  	//
    24  	{{- range lines_ (format_ .data.Script) }}
    25  	//	{{ . }}
    26  	{{- end }}
    27  	//
    28  	// Operations: {{ .data.Ops.Doubles }} squares {{ .data.Ops.Adds }} multiplies
    29  
    30  	// Allocate Temporaries.
    31  	var (
    32  		{{- range .data.Program.Temporaries }}
    33  		{{ . }} = new({{$.eName}})
    34  		{{- end -}}
    35  	)
    36  
    37  	// var {{range $i, $e := .data.Program.Temporaries }}{{ $e }} {{- if last_ $i $.data.Program.Temporaries}} {{$.eName}} {{- else }}, {{- end}}{{- end -}}
    38  
    39  	{{ range $i := .data.Program.Instructions }}
    40  	// {{ printf "Step %d: %s = x^%#x" $i.Output.Index $i.Output (index $.data.Chain $i.Output.Index) }}
    41  	{{- with add_ $i.Op }}
    42  	{{ $i.Output }}.Mul({{ ptr_ .X }}{{ .X }}, {{ ptr_ .Y }}{{ .Y }})
    43  	{{ end -}}
    44  
    45  	{{- with double_ $i.Op }}
    46  	{{ $i.Output }}.Square({{ ptr_ .X }}{{ .X }})
    47  	{{ end -}}
    48  
    49  	{{- with shift_ $i.Op -}}
    50  	{{- $first := 0 -}}
    51  	{{- if ne $i.Output.Identifier .X.Identifier }}
    52  	{{ $i.Output }}.Square({{ ptr_ .X }}{{ .X }})
    53  	{{- $first = 1 -}}
    54  	{{- end }}
    55  	for s := {{ $first }}; s < {{ .S }}; s++ {
    56  		{{ $i.Output }}.Square({{ ptr_ $i.Output }}{{ $i.Output }})
    57  	}
    58  	{{ end -}}
    59  	{{- end }}
    60  	return z
    61  }
    62  
    63  {{end}}
    64  
    65  
    66  
    67  
    68  
    69  `