github.com/status-im/status-go@v1.1.0/mailserver/db_key.go (about)

     1  package mailserver
     2  
     3  import (
     4  	"encoding/binary"
     5  	"errors"
     6  
     7  	"github.com/status-im/status-go/eth-node/types"
     8  )
     9  
    10  const (
    11  	// DBKeyLength is a size of the envelope key.
    12  	DBKeyLength  = types.HashLength + timestampLength + types.TopicLength
    13  	CursorLength = types.HashLength + timestampLength
    14  )
    15  
    16  var (
    17  	// ErrInvalidByteSize is returned when DBKey can't be created
    18  	// from a byte slice because it has invalid length.
    19  	ErrInvalidByteSize = errors.New("byte slice has invalid length")
    20  )
    21  
    22  // DBKey key to be stored in a db.
    23  type DBKey struct {
    24  	raw []byte
    25  }
    26  
    27  // Bytes returns a bytes representation of the DBKey.
    28  func (k *DBKey) Bytes() []byte {
    29  	return k.raw
    30  }
    31  
    32  func (k *DBKey) Topic() types.TopicType {
    33  	return types.BytesToTopic(k.raw[timestampLength+types.HashLength:])
    34  }
    35  
    36  func (k *DBKey) EnvelopeHash() types.Hash {
    37  	return types.BytesToHash(k.raw[timestampLength : types.HashLength+timestampLength])
    38  }
    39  
    40  func (k *DBKey) Cursor() []byte {
    41  	// We don't use the whole cursor for backward compatibility (also it's not needed)
    42  	return k.raw[:CursorLength]
    43  }
    44  
    45  // NewDBKey creates a new DBKey with the given values.
    46  func NewDBKey(timestamp uint32, topic types.TopicType, h types.Hash) *DBKey {
    47  	var k DBKey
    48  	k.raw = make([]byte, DBKeyLength)
    49  	binary.BigEndian.PutUint32(k.raw, timestamp)
    50  	copy(k.raw[timestampLength:], h[:])
    51  	copy(k.raw[timestampLength+types.HashLength:], topic[:])
    52  	return &k
    53  }