github.com/onosproject/onos-api/go@v0.10.32/onos/ransim/types/uint24.go (about)

     1  // SPDX-FileCopyrightText: 2020-present Open Networking Foundation <info@opennetworking.org>
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package types
     6  
     7  import (
     8  	"bytes"
     9  	"encoding/binary"
    10  	"strconv"
    11  )
    12  
    13  const (
    14  	// MaxUint24 maximum value of uint24 variable
    15  	MaxUint24 = 1<<24 - 1
    16  )
    17  
    18  // Uint24 unti24 type
    19  type Uint24 [3]uint8
    20  
    21  // NewUint24 creates a new uint24 type
    22  func NewUint24(val uint32) *Uint24 {
    23  	var u = new(Uint24)
    24  	u.Set(val)
    25  	return u
    26  }
    27  
    28  // Value returns value
    29  func (u *Uint24) Value() Uint24 {
    30  	return *u
    31  }
    32  
    33  // Set sets uint24 value
    34  func (u *Uint24) Set(val uint32) {
    35  	if val > MaxUint24 {
    36  		return
    37  	}
    38  	(*u)[0] = uint8(val & 0xFF)
    39  	(*u)[1] = uint8((val >> 8) & 0xFF)
    40  	(*u)[2] = uint8((val >> 16) & 0xFF)
    41  }
    42  
    43  // Uint32 converts uint24 to uint32
    44  func (u Uint24) Uint32() uint32 {
    45  	return uint32(u[0]) | uint32(u[1])<<8 | uint32(u[2])<<16
    46  }
    47  
    48  // String converts uint24 to string
    49  func (u Uint24) String() string {
    50  	return strconv.Itoa(int(u.Uint32()))
    51  }
    52  
    53  // ToBytes converts uint24 to bytes array
    54  func (u Uint24) ToBytes() []byte {
    55  	var buf = &bytes.Buffer{}
    56  	if err := binary.Write(buf, binary.BigEndian, u); err != nil {
    57  		return nil
    58  	}
    59  	return buf.Bytes()
    60  }
    61  
    62  // Uint24ToUint32 converts uint24 uint32
    63  func Uint24ToUint32(val []byte) uint32 {
    64  	r := uint32(0)
    65  	for i := uint32(0); i < 3; i++ {
    66  		r |= uint32(val[i]) << (8 * i)
    67  	}
    68  	return r
    69  }