git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/countries/countryint32.go (about)

     1  package countries
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"fmt"
     6  )
     7  
     8  // CountryInt32 is a tpye that store a 2-letters country code as an int32.
     9  // The goal is to have more efficient database operations than using the a basic TEXT
    10  type CountryInt32 string
    11  
    12  // Scan implements sql.Scanner so CountryInt32 can be read from databases transparently.
    13  func (country *CountryInt32) Scan(src interface{}) (err error) {
    14  	switch src := src.(type) {
    15  	case int32:
    16  		value := make([]rune, 2)
    17  		value[0] = rune(src >> 8)
    18  		value[1] = rune(int8(src))
    19  		*country = CountryInt32(string(value))
    20  
    21  	default:
    22  		return fmt.Errorf("Scan: unable to scan type %T into CountryInt32", src)
    23  	}
    24  	return
    25  }
    26  
    27  // Value implements sql.Valuer so that CountryInt32 can be written to databases
    28  func (country CountryInt32) Value() (driver.Value, error) {
    29  	var value int32
    30  
    31  	value |= int32(country[0]) << 8
    32  	value |= int32(country[1])
    33  
    34  	return value, nil
    35  }