blob: 64f46272aedc1408c709066d591f8274bd34b9a6 [file] [log] [blame]
Joey Armstronge8c091f2023-01-17 16:56:26 -05001/*
2Copyright 2014 The Camlistore Authors
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package internal
18
19import (
20 "sync"
21 "sync/atomic"
22)
23
24// A Once will perform a successful action exactly once.
25//
26// Unlike a sync.Once, this Once's func returns an error
27// and is re-armed on failure.
28type Once struct {
29 m sync.Mutex
30 done uint32
31}
32
33// Do calls the function f if and only if Do has not been invoked
34// without error for this instance of Once. In other words, given
35// var once Once
36// if once.Do(f) is called multiple times, only the first call will
37// invoke f, even if f has a different value in each invocation unless
38// f returns an error. A new instance of Once is required for each
39// function to execute.
40//
41// Do is intended for initialization that must be run exactly once. Since f
42// is niladic, it may be necessary to use a function literal to capture the
43// arguments to a function to be invoked by Do:
44// err := config.once.Do(func() error { return config.init(filename) })
45func (o *Once) Do(f func() error) error {
46 if atomic.LoadUint32(&o.done) == 1 {
47 return nil
48 }
49 // Slow-path.
50 o.m.Lock()
51 defer o.m.Unlock()
52 var err error
53 if o.done == 0 {
54 err = f()
55 if err == nil {
56 atomic.StoreUint32(&o.done, 1)
57 }
58 }
59 return err
60}