Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 package errors | |
| 6 | |
| 7 import ( | |
| 8 "sync" | |
| 9 ) | |
| 10 | |
| 11 // LazyMultiError is a lazily-constructed MultiError. | |
| 12 // | |
| 13 // LazyMultiError is like MultiError, except that you know the ultimate size up | |
| 14 // front, and then you call Assign for each error encountered, and it's | |
| 15 // potential index. The underlying MultiError will only be allocated if one of | |
| 16 // the Assign'd errors is non-nil. Similarly, Get will retrieve either the | |
| 17 // allocated MultiError, or nil if no error was encountered. | |
| 18 // Build one with NewLazy. | |
|
tandrii(chromium)
2015/08/14 17:14:30
nit: NewLazyMultiError
| |
| 19 type LazyMultiError interface { | |
| 20 // Assign semantically assigns the error to the given index in the Multi Error. | |
| 21 // If the error is nil, no action is taken. Otherwise the MultiError is | |
| 22 // allocated to its full size (if not already), and the error assigned i nto | |
| 23 // it. | |
| 24 // | |
| 25 // Returns true iff err != nil (i.e. "was it assigned?"), so you can use this | |
| 26 // like: | |
| 27 // if !lme.Assign(i, err) { | |
| 28 // // stuff requiring err == nil | |
| 29 // } | |
| 30 Assign(int, error) bool | |
| 31 | |
| 32 // GetOne returns the error at the given index (which may be nil) | |
| 33 GetOne(int) error | |
| 34 | |
| 35 // Get returns the MultiError, or nil, if no non-nil error was Assign'd. | |
| 36 Get() error | |
| 37 } | |
| 38 | |
| 39 type lazyMultiError struct { | |
| 40 sync.Mutex | |
| 41 | |
| 42 size int | |
| 43 me MultiError | |
| 44 } | |
| 45 | |
| 46 // NewLazyMultiError makes a new LazyMultiError of the provided size. | |
| 47 func NewLazyMultiError(size int) *lazyMultiError { | |
| 48 return &lazyMultiError{size: size} | |
| 49 } | |
| 50 | |
| 51 func (e *lazyMultiError) Assign(i int, err error) bool { | |
| 52 if err == nil { | |
| 53 return false | |
| 54 } | |
| 55 e.Lock() | |
| 56 defer e.Unlock() | |
| 57 if e.me == nil { | |
| 58 e.me = make(MultiError, e.size) | |
| 59 } | |
| 60 e.me[i] = err | |
| 61 return true | |
| 62 } | |
| 63 | |
| 64 func (e *lazyMultiError) GetOne(i int) error { | |
| 65 e.Lock() | |
| 66 defer e.Unlock() | |
| 67 if e.me == nil { | |
| 68 return nil | |
| 69 } | |
| 70 return e.me[i] | |
| 71 } | |
| 72 | |
| 73 func (e *lazyMultiError) Get() error { | |
| 74 e.Lock() | |
| 75 defer e.Unlock() | |
| 76 if e.me == nil { | |
| 77 return nil | |
| 78 } | |
| 79 return e.me | |
| 80 } | |
| OLD | NEW |