blob: d42a3671e721cf815c34a5e17f04dca0ee0e7f3f [file] [log] [blame]
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -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 store
6
Sergey Rogulenkoa53e60f2015-05-22 11:05:01 -07007import (
8 "v.io/v23/verror"
9)
10
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070011func RunInTransaction(st Store, fn func(st StoreReadWriter) error) error {
Sergey Rogulenko8a1ae3a2015-05-29 17:13:44 -070012 // TODO(rogulenko): We should eventually give up with
13 // ErrConcurrentTransaction.
14 // TODO(rogulenko): Fail on RPC errors.
15 for {
16 tx := st.NewTransaction()
17 if err := fn(tx); err != nil {
18 tx.Abort()
19 return err
20 }
21 err := tx.Commit()
22 if err == nil {
23 return nil
24 }
25 if verror.ErrorID(err) == ErrConcurrentTransaction.ID {
26 continue
27 }
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070028 return err
29 }
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070030}
31
32// CopyBytes copies elements from a source slice into a destination slice.
33// The returned slice may be a sub-slice of dst if dst was large enough to hold
34// src. Otherwise, a newly allocated slice will be returned.
Sergey Rogulenko0dbfe072015-05-19 20:10:18 -070035// TODO(rogulenko): add some tests.
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070036func CopyBytes(dst, src []byte) []byte {
37 if cap(dst) < len(src) {
38 newlen := cap(dst)*2 + 2
39 if newlen < len(src) {
40 newlen = len(src)
41 }
42 dst = make([]byte, newlen)
43 }
Sergey Rogulenko0dbfe072015-05-19 20:10:18 -070044 dst = dst[:len(src)]
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070045 copy(dst, src)
Sergey Rogulenko0dbfe072015-05-19 20:10:18 -070046 return dst
Adam Sadovskyc18c8ca2015-05-08 18:05:46 -070047}