github.com/higress-group/nottinygc@v0.0.0-20231101025119-e93c4c2f8520/bitmap_test.go (about)

     1  // Copyright wasilibs authors
     2  // SPDX-License-Identifier: MIT
     3  
     4  package nottinygc
     5  
     6  import (
     7  	"fmt"
     8  	"testing"
     9  )
    10  
    11  func TestBitmap32Bits(t *testing.T) {
    12  	tests := []uintptr{
    13  		0,
    14  		0b1,
    15  		0b101,
    16  		0b111,
    17  		0b0001,
    18  		0b1000001,
    19  		0xFFFFFFFF,
    20  		0x11111111,
    21  		0x01010101,
    22  		0x0F0F0F0F,
    23  	}
    24  
    25  	for _, tc := range tests {
    26  		tc := tc
    27  		t.Run(fmt.Sprintf("%v", tc), func(t *testing.T) {
    28  			bm := newBitmap(32)
    29  			if len(bm.words) != 1 {
    30  				t.Fatalf("expected 1 word, got %v", len(bm.words))
    31  			}
    32  			for i := 0; i < 32; i++ {
    33  				if tc&(1<<i) != 0 {
    34  					bm.set(uintptr(i))
    35  				}
    36  			}
    37  
    38  			for i := 0; i < 32; i++ {
    39  				got := bm.get(uintptr(i))
    40  				if tc&(1<<i) != 0 {
    41  					if got == 0 {
    42  						t.Fatalf("expected bit %v to be set", i)
    43  					}
    44  				} else {
    45  					if got != 0 {
    46  						t.Fatalf("expected bit %v to be unset", i)
    47  					}
    48  				}
    49  			}
    50  		})
    51  	}
    52  }
    53  
    54  // Test for multiple words, we pick larger than 64-bits to have more than one word on Go
    55  // as well. We don't actually run CI with Go but it can be helpful for development.
    56  func TestBitmap128Bits(t *testing.T) {
    57  	// We'll just repeat these.
    58  	tests := []uintptr{
    59  		0,
    60  		0b1,
    61  		0b101,
    62  		0b111,
    63  		0b0001,
    64  		0b1000001,
    65  		0xFFFFFFFF,
    66  		0x11111111,
    67  		0x01010101,
    68  		0x0F0F0F0F,
    69  	}
    70  
    71  	for _, tc := range tests {
    72  		tc := tc
    73  		t.Run(fmt.Sprintf("%v", tc), func(t *testing.T) {
    74  			bm := newBitmap(128)
    75  			if cppWordsz == 32 && len(bm.words) != 4 || cppWordsz == 64 && len(bm.words) != 2 {
    76  				t.Fatalf("got %v words", len(bm.words))
    77  			}
    78  			for j := 0; j < 4; j++ {
    79  				for i := 0; i < 32; i++ {
    80  					if tc&(1<<(32*j+i)) != 0 {
    81  						bm.set(uintptr(i))
    82  					}
    83  				}
    84  			}
    85  
    86  			for j := 0; j < 4; j++ {
    87  				for i := 0; i < 32; i++ {
    88  					got := bm.get(uintptr(32*j + i))
    89  					if tc&(1<<(32*j+i)) != 0 {
    90  						if got == 0 {
    91  							t.Fatalf("expected bit %v to be set", i)
    92  						}
    93  					} else {
    94  						if got != 0 {
    95  							t.Fatalf("expected bit %v to be unset", i)
    96  						}
    97  					}
    98  				}
    99  			}
   100  		})
   101  	}
   102  }