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

     1  package element
     2  
     3  const OpsNoAsm = `
     4  
     5  import "math/bits"
     6  
     7  {{ $mulConsts := list 3 5 13 }}
     8  {{- range $i := $mulConsts }}
     9  
    10  // MulBy{{$i}} x *= {{$i}} (mod q)
    11  func MulBy{{$i}}(x *{{$.ElementName}}) {
    12  	{{- if eq 1 $.NbWords}}
    13  	var y {{$.ElementName}}
    14  	y.SetUint64({{$i}})
    15  	x.Mul(x, &y)
    16  	{{- else}}
    17  		{{- if eq $i 3}}
    18  			_x := *x
    19  			x.Double(x).Add(x, &_x)
    20  		{{- else if eq $i 5}}
    21  			_x := *x
    22  			x.Double(x).Double(x).Add(x, &_x)
    23  		{{- else if eq $i 13}}
    24  			var y = {{$.ElementName}}{
    25  				{{- range $i := $.Thirteen}}
    26  				{{$i}},{{end}}
    27  			}
    28  			x.Mul(x, &y)
    29  		{{- else }}
    30  			NOT IMPLEMENTED
    31  		{{- end}}
    32  	{{- end}}
    33  }
    34  
    35  {{- end}}
    36  
    37  // Butterfly sets
    38  //  a = a + b (mod q)
    39  //  b = a - b (mod q)
    40  func Butterfly(a, b *{{.ElementName}}) {
    41  	_butterflyGeneric(a, b)
    42  }
    43  
    44  
    45  func fromMont(z *{{.ElementName}} ) {
    46  	_fromMontGeneric(z)
    47  }
    48  
    49  func reduce(z *{{.ElementName}})  {
    50  	_reduceGeneric(z)
    51  }
    52  
    53  
    54  
    55  // Mul z = x * y (mod q)
    56  {{- if $.NoCarry}}
    57  //
    58  // x and y must be less than q
    59  {{- end }}
    60  func (z *{{.ElementName}}) Mul(x, y *{{.ElementName}}) *{{.ElementName}} {
    61  	{{- if eq $.NbWords 1}}
    62  		{{ template "mul_cios_one_limb" dict "all" . "V1" "x" "V2" "y" }}
    63  	{{- else }}
    64  		{{ mul_doc $.NoCarry }}
    65  		{{- if $.NoCarry}}
    66  			{{ template "mul_nocarry" dict "all" . "V1" "x" "V2" "y"}}
    67  		{{- else}}
    68  			{{ template "mul_cios" dict "all" . "V1" "x" "V2" "y" "ReturnZ" true}}
    69  		{{- end}}
    70  		{{ template "reduce"  . }}
    71  	{{- end }}
    72  	return z
    73  }
    74  
    75  // Square z = x * x (mod q)
    76  {{- if $.NoCarry}}
    77  //
    78  // x must be less than q
    79  {{- end }}
    80  func (z *{{.ElementName}}) Square(x *{{.ElementName}}) *{{.ElementName}} {
    81  	// see Mul for algorithm documentation
    82  	{{- if eq $.NbWords 1}}
    83  		{{ template "mul_cios_one_limb" dict "all" . "V1" "x" "V2" "x" }}
    84  	{{- else }}
    85  		{{- if $.NoCarry}}
    86  			{{ template "mul_nocarry" dict "all" . "V1" "x" "V2" "x"}}
    87  		{{- else}}
    88  			{{ template "mul_cios" dict "all" . "V1" "x" "V2" "x" "ReturnZ" true}}
    89  		{{- end}}
    90  		{{ template "reduce"  . }}
    91  	{{- end }}
    92  	return z
    93  }
    94  
    95  `