github.com/cloudflare/circl@v1.5.0/pke/kyber/kyber512/internal/mat.go (about)

     1  package internal
     2  
     3  import (
     4  	"github.com/cloudflare/circl/pke/kyber/internal/common"
     5  )
     6  
     7  // A k by k matrix of polynomials.
     8  type Mat [K]Vec
     9  
    10  // Expands the given seed to the corresponding matrix A or its transpose Aᵀ.
    11  func (m *Mat) Derive(seed *[32]byte, transpose bool) {
    12  	if !common.DeriveX4Available {
    13  		if transpose {
    14  			for i := 0; i < K; i++ {
    15  				for j := 0; j < K; j++ {
    16  					m[i][j].DeriveUniform(seed, uint8(i), uint8(j))
    17  				}
    18  			}
    19  		} else {
    20  			for i := 0; i < K; i++ {
    21  				for j := 0; j < K; j++ {
    22  					m[i][j].DeriveUniform(seed, uint8(j), uint8(i))
    23  				}
    24  			}
    25  		}
    26  		return
    27  	}
    28  
    29  	var ps [4]*common.Poly
    30  	var xs [4]uint8
    31  	var ys [4]uint8
    32  	x := uint8(0)
    33  	y := uint8(0)
    34  
    35  	for x != K {
    36  		idx := 0
    37  		for ; idx < 4; idx++ {
    38  			ps[idx] = &m[x][y]
    39  
    40  			if transpose {
    41  				xs[idx] = x
    42  				ys[idx] = y
    43  			} else {
    44  				xs[idx] = y
    45  				ys[idx] = x
    46  			}
    47  
    48  			y++
    49  			if y == K {
    50  				x++
    51  				y = 0
    52  
    53  				if x == K {
    54  					if idx == 0 {
    55  						// If there is just one left, then a plain DeriveUniform
    56  						// is quicker than the X4 variant.
    57  						ps[0].DeriveUniform(seed, xs[0], ys[0])
    58  						return
    59  					}
    60  
    61  					for idx++; idx < 4; idx++ {
    62  						ps[idx] = nil
    63  					}
    64  
    65  					break
    66  				}
    67  			}
    68  		}
    69  
    70  		common.PolyDeriveUniformX4(ps, seed, xs, ys)
    71  	}
    72  }
    73  
    74  // Transposes A in place.
    75  func (m *Mat) Transpose() {
    76  	for i := 0; i < K-1; i++ {
    77  		for j := i + 1; j < K; j++ {
    78  			t := m[i][j]
    79  			m[i][j] = m[j][i]
    80  			m[j][i] = t
    81  		}
    82  	}
    83  }