github.com/grailbio/base@v0.0.11/diagnostic/stringintern/intern_test.go (about)

     1  package stringintern
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/grailbio/base/diagnostic/memsize"
     7  )
     8  
     9  type AB struct {
    10  	A string
    11  	B string
    12  }
    13  
    14  // return a string with the same content which does not share the same underlying memory.
    15  func unintern(x string) string {
    16  	ret := ""
    17  	for _, t := range x {
    18  		ret = ret + string(t)
    19  	}
    20  	return ret
    21  }
    22  
    23  type Test struct {
    24  	x                     []interface{}
    25  	sizeBefore, sizeAfter int
    26  }
    27  
    28  func TestBasic(t *testing.T) {
    29  	var int64Var int = 3
    30  	tests := []Test{
    31  		{
    32  			x:          []interface{}{&AB{"abc", unintern("abc")}},
    33  			sizeBefore: 86,
    34  			sizeAfter:  83,
    35  		},
    36  		{
    37  			x:          []interface{}{&map[int]string{1: "abc", 2: unintern("abc")}},
    38  			sizeBefore: 110,
    39  			sizeAfter:  107,
    40  		},
    41  		{
    42  			x:          []interface{}{&int64Var},
    43  			sizeBefore: 56,
    44  			sizeAfter:  56,
    45  		},
    46  	}
    47  
    48  	for _, test := range tests {
    49  		runTest(test, t)
    50  	}
    51  }
    52  
    53  func TestCircular(t *testing.T) {
    54  	type Circular struct {
    55  		A, B string
    56  		ptr  *Circular
    57  	}
    58  
    59  	type Nested struct {
    60  		X Circular
    61  	}
    62  
    63  	circ := Circular{
    64  		A: "abc",
    65  		B: unintern("abc"),
    66  	}
    67  	circ.ptr = &circ
    68  
    69  	nested := Nested{X: Circular{
    70  		A: "abc",
    71  		B: unintern("abc"),
    72  	}}
    73  	nested.X.ptr = &nested.X
    74  
    75  	tests := []Test{
    76  		{
    77  			x:          []interface{}{&circ},
    78  			sizeBefore: 94,
    79  			sizeAfter:  91,
    80  		},
    81  		{
    82  			x:          []interface{}{&nested},
    83  			sizeBefore: 94,
    84  			sizeAfter:  91,
    85  		},
    86  	}
    87  
    88  	for _, test := range tests {
    89  		runTest(test, t)
    90  	}
    91  }
    92  
    93  func runTest(test Test, t *testing.T) {
    94  	sizeBefore := memsize.DeepSize(&test.x)
    95  	Intern(test.x...)
    96  	sizeAfter := memsize.DeepSize(&test.x)
    97  	if sizeBefore != test.sizeBefore {
    98  		t.Errorf("sizeBefore:  expected=%d, got=%d", test.sizeBefore, sizeBefore)
    99  	}
   100  	if sizeAfter != test.sizeAfter {
   101  		t.Errorf("sizeAfter:  expected=%d, got=%d", test.sizeAfter, sizeAfter)
   102  	}
   103  }