Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 1 | // 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 | |
| 5 | package store |
| 6 | |
Sergey Rogulenko | a53e60f | 2015-05-22 11:05:01 -0700 | [diff] [blame] | 7 | import ( |
| 8 | "v.io/v23/verror" |
| 9 | ) |
| 10 | |
Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 11 | func RunInTransaction(st Store, fn func(st StoreReadWriter) error) error { |
Sergey Rogulenko | 8a1ae3a | 2015-05-29 17:13:44 -0700 | [diff] [blame] | 12 | // 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 Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 28 | return err |
| 29 | } |
Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 30 | } |
| 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 Rogulenko | 0dbfe07 | 2015-05-19 20:10:18 -0700 | [diff] [blame] | 35 | // TODO(rogulenko): add some tests. |
Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 36 | func 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 Rogulenko | 0dbfe07 | 2015-05-19 20:10:18 -0700 | [diff] [blame] | 44 | dst = dst[:len(src)] |
Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 45 | copy(dst, src) |
Sergey Rogulenko | 0dbfe07 | 2015-05-19 20:10:18 -0700 | [diff] [blame] | 46 | return dst |
Adam Sadovsky | c18c8ca | 2015-05-08 18:05:46 -0700 | [diff] [blame] | 47 | } |