github.com/mitranim/gg@v0.1.17/gsql/gsql_internal_test.go (about)

     1  package gsql
     2  
     3  import (
     4  	r "reflect"
     5  	"testing"
     6  
     7  	"github.com/mitranim/gg"
     8  	"github.com/mitranim/gg/gtest"
     9  )
    10  
    11  type Inner struct {
    12  	InnerId   string  `db:"inner_id"`
    13  	InnerName *string `db:"inner_name"`
    14  }
    15  
    16  type Outer struct {
    17  	OuterId   int64         `db:"outer_id"`
    18  	OuterName string        `db:"outer_name"`
    19  	InnerZop  gg.Zop[Inner] `db:"inner_zop"`
    20  	Inner     Inner         `db:"inner"`
    21  }
    22  
    23  func Test_structMetaCache(t *testing.T) {
    24  	defer gtest.Catch(t)
    25  
    26  	gtest.Equal(
    27  		typeMetaCache.Get(gg.Type[Outer]()),
    28  		typeMeta{
    29  			`outer_id`:             []int{0},
    30  			`outer_name`:           []int{1},
    31  			`inner_zop.inner_id`:   []int{2, 0, 0},
    32  			`inner_zop.inner_name`: []int{2, 0, 1},
    33  			`inner.inner_id`:       []int{3, 0},
    34  			`inner.inner_name`:     []int{3, 1},
    35  		},
    36  	)
    37  }
    38  
    39  /*
    40  Used by `scanValsReflect`. This demonstrates doubling behavior of
    41  `reflect.Value.Grow`. Our choice of implementation relies on this behavior. If
    42  `reflect.Value.Grow` allocated precisely the requested amount of additional
    43  capacity, which in our case is 1, we would have to change our strategy.
    44  
    45  Compare our `gg.GrowCap`, which behaves like `reflect.Value.Grow`, and
    46  `gg.GrowCapExact`, which behaves in a way that would be detrimental for
    47  the kind of algorithm we use here.
    48  */
    49  func Test_reflect_slice_grow_alloc(t *testing.T) {
    50  	defer gtest.Catch(t)
    51  
    52  	var tar []int
    53  
    54  	val := r.ValueOf(&tar).Elem()
    55  
    56  	test := func(diff, total int) {
    57  		prevLen := len(tar)
    58  
    59  		val.Grow(diff)
    60  		gtest.Eq(val.Len(), len(tar))
    61  		gtest.Eq(val.Cap(), cap(tar))
    62  		gtest.Eq(cap(tar), total)
    63  		gtest.Eq(len(tar), prevLen)
    64  
    65  		val.SetLen(total)
    66  		gtest.Eq(val.Len(), len(tar))
    67  		gtest.Eq(len(tar), total)
    68  	}
    69  
    70  	test(0, 0)
    71  	test(1, 1)
    72  	test(1, 2)
    73  	test(1, 4)
    74  	test(1, 8)
    75  	test(1, 16)
    76  	test(1, 32)
    77  }