github.com/wasilibs/nottinygc@v0.7.2-0.20240312114022-d59c9478ef51/bitmap.go (about)

     1  // Copyright wasilibs authors
     2  // SPDX-License-Identifier: MIT
     3  
     4  package nottinygc
     5  
     6  import "unsafe"
     7  
     8  // CPP_WORDSZ is a simple integer constant representing the word size
     9  const cppWordsz = unsafe.Sizeof(uintptr(0)) * 8
    10  
    11  type gcBitmap struct {
    12  	words []uintptr
    13  }
    14  
    15  func newBitmap(size uintptr) gcBitmap {
    16  	bmSize := gcBitmapSize(size)
    17  	wordsArr := cmalloc(bmSize * unsafe.Sizeof(uintptr(0)))
    18  	words := unsafe.Slice((*uintptr)(wordsArr), bmSize)
    19  	for i := 0; i < len(words); i++ {
    20  		words[i] = 0
    21  	}
    22  	return gcBitmap{words: words}
    23  }
    24  
    25  func (b gcBitmap) set(idx uintptr) {
    26  	b.words[idx/cppWordsz] |= 1 << (idx % cppWordsz)
    27  }
    28  
    29  func (b gcBitmap) get(idx uintptr) uintptr {
    30  	return (b.words[idx/cppWordsz] >> (idx % cppWordsz)) & 1
    31  }
    32  
    33  func (b gcBitmap) free() {
    34  	cfree(unsafe.Pointer(&b.words[0]))
    35  }
    36  
    37  func gcBitmapSize(size uintptr) uintptr {
    38  	return (size + cppWordsz - 1) / cppWordsz
    39  }