blob: cd37d3eac77791703c0d22fc9b181bad2cb05625 [file] [log] [blame]
Adam Sadovsky8db74432015-05-29 17:37:32 -07001// Copyright 2015 The Vanadium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package watchable
6
7// TODO(sadovsky): Avoid copying back and forth between []byte's and strings.
8// We should probably convert incoming strings to []byte's as early as possible,
9// and deal exclusively in []byte's internally.
10
11import (
12 "fmt"
13 "math/rand"
14 "time"
15
16 "v.io/syncbase/x/ref/services/syncbase/server/util"
17 "v.io/syncbase/x/ref/services/syncbase/store"
18)
19
20var rng *rand.Rand = rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
21
22func makeVersionKey(key []byte) []byte {
23 return []byte(join(util.VersionPrefix, string(key)))
24}
25
26func makeAtVersionKey(key, version []byte) []byte {
27 return []byte(join(string(key), string(version)))
28}
29
30func getVersion(st store.StoreReader, key []byte) ([]byte, error) {
31 return st.Get(makeVersionKey(key), nil)
32}
33
34func getAtVersion(st store.StoreReader, key, valbuf, version []byte) ([]byte, error) {
35 return st.Get(makeAtVersionKey(key, version), valbuf)
36}
37
38func getVersioned(st store.StoreReader, key, valbuf []byte) ([]byte, error) {
39 checkTransactionOrSnapshot(st)
40 version, err := getVersion(st, key)
41 if err != nil {
42 return valbuf, err
43 }
44 return getAtVersion(st, key, valbuf, version)
45}
46
47func putVersioned(tx store.Transaction, key, value []byte) error {
48 version := []byte(fmt.Sprintf("%x", rng.Int63()))
49 if err := tx.Put(makeVersionKey(key), version); err != nil {
50 return err
51 }
52 return tx.Put(makeAtVersionKey(key, version), value)
53}
54
55func deleteVersioned(tx store.Transaction, key []byte) error {
56 return tx.Delete(makeVersionKey(key))
57}
58
59func checkTransactionOrSnapshot(st store.StoreReader) {
60 _, isTransaction := st.(store.Transaction)
61 _, isSnapshot := st.(store.Snapshot)
62 if !isTransaction && !isSnapshot {
63 panic("neither a Transaction nor a Snapshot")
64 }
65}
66
67func join(parts ...string) string {
68 return util.JoinKeyParts(parts...)
69}
70
71func split(key string) []string {
72 return util.SplitKeyParts(key)
73}