github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/nomad/structs/bitmap_test.go (about)

     1  package structs
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/hashicorp/nomad/ci"
     8  )
     9  
    10  func TestBitmap(t *testing.T) {
    11  	ci.Parallel(t)
    12  
    13  	// Check invalid sizes
    14  	_, err := NewBitmap(0)
    15  	if err == nil {
    16  		t.Fatalf("bad")
    17  	}
    18  	_, err = NewBitmap(7)
    19  	if err == nil {
    20  		t.Fatalf("bad")
    21  	}
    22  
    23  	// Create a normal bitmap
    24  	var s uint = 256
    25  	b, err := NewBitmap(s)
    26  	if err != nil {
    27  		t.Fatalf("err: %v", err)
    28  	}
    29  
    30  	if b.Size() != s {
    31  		t.Fatalf("bad size")
    32  	}
    33  
    34  	// Set a few bits
    35  	b.Set(0)
    36  	b.Set(255)
    37  
    38  	// Verify the bytes
    39  	if b[0] == 0 {
    40  		t.Fatalf("bad")
    41  	}
    42  	if !b.Check(0) {
    43  		t.Fatalf("bad")
    44  	}
    45  
    46  	// Verify the bytes
    47  	if b[len(b)-1] == 0 {
    48  		t.Fatalf("bad")
    49  	}
    50  	if !b.Check(255) {
    51  		t.Fatalf("bad")
    52  	}
    53  
    54  	// All other bits should be unset
    55  	for i := 1; i < 255; i++ {
    56  		if b.Check(uint(i)) {
    57  			t.Fatalf("bad")
    58  		}
    59  	}
    60  
    61  	// Check the indexes
    62  	idxs := b.IndexesInRange(true, 0, 500)
    63  	expected := []int{0, 255}
    64  	if !reflect.DeepEqual(idxs, expected) {
    65  		t.Fatalf("bad: got %#v; want %#v", idxs, expected)
    66  	}
    67  
    68  	idxs = b.IndexesInRange(true, 1, 255)
    69  	expected = []int{255}
    70  	if !reflect.DeepEqual(idxs, expected) {
    71  		t.Fatalf("bad: got %#v; want %#v", idxs, expected)
    72  	}
    73  
    74  	idxs = b.IndexesInRange(false, 0, 256)
    75  	if len(idxs) != 254 {
    76  		t.Fatalf("bad")
    77  	}
    78  
    79  	idxs = b.IndexesInRange(false, 100, 200)
    80  	if len(idxs) != 101 {
    81  		t.Fatalf("bad")
    82  	}
    83  
    84  	// Check the copy is correct
    85  	b2, err := b.Copy()
    86  	if err != nil {
    87  		t.Fatalf("bad: %v", err)
    88  	}
    89  
    90  	if !reflect.DeepEqual(b, b2) {
    91  		t.Fatalf("bad")
    92  	}
    93  
    94  	// Clear
    95  	b.Clear()
    96  
    97  	// All bits should be unset
    98  	for i := 0; i < 256; i++ {
    99  		if b.Check(uint(i)) {
   100  			t.Fatalf("bad")
   101  		}
   102  	}
   103  
   104  	// Set a few bits
   105  	b.Set(0)
   106  	b.Set(255)
   107  	b.Unset(0)
   108  	b.Unset(255)
   109  
   110  	// Clear the bits
   111  	if b[0] != 0 {
   112  		t.Fatalf("bad")
   113  	}
   114  	if b.Check(0) {
   115  		t.Fatalf("bad")
   116  	}
   117  
   118  	// Verify the bytes
   119  	if b[len(b)-1] != 0 {
   120  		t.Fatalf("bad")
   121  	}
   122  	if b.Check(255) {
   123  		t.Fatalf("bad")
   124  	}
   125  }