gitee.com/quant1x/num@v0.3.2/repeat.go (about)

     1  package num
     2  
     3  import (
     4  	"gitee.com/quant1x/num/binary"
     5  	"gitee.com/quant1x/num/vectors"
     6  	"gitee.com/quant1x/num/x32"
     7  	"gitee.com/quant1x/num/x64"
     8  )
     9  
    10  // Repeat 构造n长度的x的泛型切片
    11  func Repeat[E BaseType](x E, n int) []E {
    12  	if n < 1 {
    13  		return []E{}
    14  	}
    15  	return v2Repeat[E](x, n)
    16  }
    17  
    18  func v1Repeat[E BaseType](x E, n int) []E {
    19  	var d any
    20  	switch v := any(x).(type) {
    21  	case float32:
    22  		d = x32.Repeat(v, n)
    23  	case float64:
    24  		d = x64.Repeat(v, n)
    25  	default:
    26  		// 剩下非float32和float64, 循环吧
    27  		d = []E{}
    28  		m := make([]E, n)
    29  		for i := 0; i < n; i++ {
    30  			m[i] = x
    31  		}
    32  		d = m
    33  	}
    34  	return d.([]E)
    35  }
    36  
    37  // 浮点加速, 其它类型使用2倍速copy
    38  func v2Repeat[E BaseType](x E, n int) []E {
    39  	var d any
    40  	switch v := any(x).(type) {
    41  	case float32:
    42  		d = x32.Repeat(v, n)
    43  	case float64:
    44  		d = x64.Repeat(v, n)
    45  	default:
    46  		d = v5Repeat(x, n)
    47  	}
    48  	return d.([]E)
    49  }
    50  
    51  func v3Repeat[E BaseType](x E, n int) []E {
    52  	data := binary.ToBytes(x)
    53  	m := binary.Repeat(data, n)
    54  	return binary.ToSlice[E](m, n)
    55  }
    56  
    57  func v4Repeat[E Number](x E, n int) []E {
    58  	s := make([]E, n)
    59  	for i := 0; i < n; i++ {
    60  		s[i] = x
    61  	}
    62  	return s
    63  }
    64  
    65  // see bytes.Repeat
    66  func v5Repeat[E BaseType](x E, count int) []E {
    67  	s := make([]E, count)
    68  	vectors.Repeat(s, x, count)
    69  	return s
    70  }
    71  
    72  // RepeatInto 替换n长度的a的泛型切片
    73  func RepeatInto[E BaseType](s []E, a E, n int) []E {
    74  	switch fs := any(s).(type) {
    75  	case []float32:
    76  		x32.Repeat_Into(fs, any(a).(float32), n)
    77  	case []float64:
    78  		x64.Repeat_Into(fs, any(a).(float64), n)
    79  	default:
    80  		vectors.Repeat(s, a, n)
    81  	}
    82  	return s[:n]
    83  }