github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/datastore/revisions/timestamprevision.go (about)

     1  package revisions
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"time"
     7  
     8  	"github.com/authzed/spicedb/pkg/datastore"
     9  )
    10  
    11  // TimestampRevision is a revision that is a timestamp.
    12  type TimestampRevision int64
    13  
    14  // NewForTime creates a new revision for the given time.
    15  func NewForTime(time time.Time) TimestampRevision {
    16  	return TimestampRevision(time.UnixNano())
    17  }
    18  
    19  // NewForTimestamp creates a new revision for the given timestamp.
    20  func NewForTimestamp(timestampNanosec int64) TimestampRevision {
    21  	return TimestampRevision(timestampNanosec)
    22  }
    23  
    24  // parseTimestampRevisionString parses a string into a timestamp revision.
    25  func parseTimestampRevisionString(revisionStr string) (rev datastore.Revision, err error) {
    26  	parsed, err := strconv.ParseInt(revisionStr, 10, 64)
    27  	if err != nil {
    28  		return nil, fmt.Errorf("invalid integer revision: %w", err)
    29  	}
    30  
    31  	return TimestampRevision(parsed), nil
    32  }
    33  
    34  func (ir TimestampRevision) Equal(other datastore.Revision) bool {
    35  	return int64(ir) == int64(other.(TimestampRevision))
    36  }
    37  
    38  func (ir TimestampRevision) GreaterThan(other datastore.Revision) bool {
    39  	return int64(ir) > int64(other.(TimestampRevision))
    40  }
    41  
    42  func (ir TimestampRevision) LessThan(other datastore.Revision) bool {
    43  	return int64(ir) < int64(other.(TimestampRevision))
    44  }
    45  
    46  func (ir TimestampRevision) TimestampNanoSec() int64 {
    47  	return int64(ir)
    48  }
    49  
    50  func (ir TimestampRevision) String() string {
    51  	return strconv.FormatInt(int64(ir), 10)
    52  }
    53  
    54  func (ir TimestampRevision) Time() time.Time {
    55  	return time.Unix(0, int64(ir))
    56  }
    57  
    58  func (ir TimestampRevision) WithInexactFloat64() float64 {
    59  	return float64(ir)
    60  }
    61  
    62  func (ir TimestampRevision) ConstructForTimestamp(timestamp int64) WithTimestampRevision {
    63  	return TimestampRevision(timestamp)
    64  }
    65  
    66  func (ir TimestampRevision) IntegerRepresentation() (int64, uint32) {
    67  	return int64(ir), 0
    68  }
    69  
    70  var (
    71  	_ datastore.Revision    = TimestampRevision(0)
    72  	_ WithTimestampRevision = TimestampRevision(0)
    73  )
    74  
    75  // TimestampIDKeyFunc is used to create keys for timestamps.
    76  func TimestampIDKeyFunc(r TimestampRevision) int64 {
    77  	return int64(r)
    78  }
    79  
    80  // TimestampIDKeyLessThanFunc is used to create keys for timestamps.
    81  func TimestampIDKeyLessThanFunc(l, r int64) bool {
    82  	return l < r
    83  }