github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/sqlutil/types_bitmap.go (about)

     1  package sqlutil
     2  
     3  import (
     4  	"database/sql"
     5  	"database/sql/driver"
     6  
     7  	"github.com/jxskiss/gopkg/v2/internal/constraints"
     8  )
     9  
    10  // Bitmap represents a bitmap value, it implements sql/driver.Valuer and sql.Scanner.
    11  // Bitmap provides Get, Set and Clear methods to manipulate the bitmap value.
    12  type Bitmap[T constraints.Integer] struct {
    13  	val *T
    14  }
    15  
    16  // NewBitmap returns a new bitmap value.
    17  func NewBitmap[T constraints.Integer](val *T) Bitmap[T] {
    18  	return Bitmap[T]{val: val}
    19  }
    20  
    21  // Value implements driver.Valuer interface.
    22  func (b Bitmap[T]) Value() (driver.Value, error) {
    23  	var out int64
    24  	if b.val != nil {
    25  		out = int64(*b.val)
    26  	}
    27  	return out, nil
    28  }
    29  
    30  // Scan implements sql.Scanner interface.
    31  func (b *Bitmap[T]) Scan(src any) error {
    32  	var tmp sql.NullInt64
    33  	err := tmp.Scan(src)
    34  	if err == nil {
    35  		val := T(tmp.Int64)
    36  		b.val = &val
    37  	}
    38  	return err
    39  }
    40  
    41  // Get returns whether mask is set in the bitmap.
    42  func (b Bitmap[T]) Get(mask int) bool {
    43  	if b.val == nil {
    44  		return false
    45  	}
    46  	return *b.val&T(mask) != 0
    47  }
    48  
    49  // Set sets mask to the bitmap.
    50  func (b *Bitmap[T]) Set(mask int) {
    51  	if b.val == nil {
    52  		var zero T
    53  		b.val = &zero
    54  	}
    55  	*b.val |= T(mask)
    56  }
    57  
    58  // Clear clears mask from the bitmap.
    59  func (b *Bitmap[T]) Clear(mask int) {
    60  	if b.val != nil {
    61  		*b.val &= ^T(mask)
    62  	}
    63  }
    64  
    65  // Underlying returns the underlying integer value.
    66  func (b Bitmap[T]) Underlying() T {
    67  	if b.val != nil {
    68  		return *b.val
    69  	}
    70  	return 0
    71  }