github.com/searKing/golang/go@v1.2.117/exp/slices/swig.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slices 6 7 // SwigVector represents Go wrapper with std::vector<T> 8 // 9 // %include <std_vector.i> 10 // %template(vector_float) std::vector<float>; 11 // See: https://www.swig.org/Doc4.1/Go.html 12 type SwigVector[E any] interface { 13 Size() int64 14 Capacity() int64 15 Reserve(int64) 16 IsEmpty() bool 17 Clear() 18 Add(e E) 19 Get(i int) E 20 Set(i int, e E) 21 } 22 23 // FromSwigVector returns a slice mapped by v.Get() within all c in the SwigVector[E]. 24 // FromSwigVector does not modify the contents of the SwigVector[E] v; it creates a new slice. 25 func FromSwigVector[S ~[]E, E any](v SwigVector[E]) S { 26 if v == nil { 27 return nil 28 } 29 30 var s = make(S, 0, v.Size()) 31 if v.IsEmpty() || v.Size() == 0 { 32 return s 33 } 34 for i := 0; i < int(v.Size()); i++ { 35 s = append(s, v.Get(i)) 36 } 37 return s 38 } 39 40 // FromSwigVectorFunc returns a slice mapped by mapped by f(v.Get()) within all c in the SwigVector[E]. 41 // FromSwigVector does not modify the contents of the SwigVector[E] v; it creates a new slice. 42 func FromSwigVectorFunc[S ~[]R, E any, R any](v SwigVector[E], f func(E) R) S { 43 if v == nil { 44 return nil 45 } 46 47 var s = make(S, 0, v.Size()) 48 if v.IsEmpty() || v.Size() == 0 { 49 return s 50 } 51 for i := 0; i < int(v.Size()); i++ { 52 s = append(s, f(v.Get(i))) 53 } 54 return s 55 } 56 57 // ToSwigVector returns a SwigVector[E] mapped by v.Get() within all c in the slice. 58 // ToSwigVector does not modify the contents of the slice s; it modifies the SwigVector[E] v. 59 func ToSwigVector[S ~[]E, E any](s S, v SwigVector[E]) { 60 if len(s) == 0 { 61 return 62 } 63 v.Clear() 64 v.Reserve(int64(len(s))) 65 for i := range s { 66 v.Add(s[i]) 67 } 68 } 69 70 // ToSwigVectorFunc returns a SwigVector[E] mapped by f(c) within all c in the slice. 71 // ToSwigVectorFunc does not modify the contents of the slice s; it modifies the SwigVector[E] v. 72 func ToSwigVectorFunc[S ~[]E, E any, R any](s S, v SwigVector[R], f func(E) R) { 73 if len(s) == 0 { 74 return 75 } 76 v.Clear() 77 v.Reserve(int64(len(s))) 78 for i := range s { 79 v.Add(f(s[i])) 80 } 81 }