go.mway.dev/chrono@v0.6.1-0.20240126030049-189c5aef20d2/periodic/handle_options.go (about)

     1  // Copyright (c) 2023 Matt Way
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to
     5  // deal in the Software without restriction, including without limitation the
     6  // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
     7  // sell copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    18  // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    19  // IN THE THE SOFTWARE.
    20  
    21  package periodic
    22  
    23  import (
    24  	"go.mway.dev/chrono/clock"
    25  )
    26  
    27  var _defaultStartOptions = startOptions{
    28  	Clock: clock.NewMonotonicClock(),
    29  }
    30  
    31  type startOptions struct {
    32  	Clock clock.Clock
    33  }
    34  
    35  func defaultStartOptions() startOptions {
    36  	return _defaultStartOptions
    37  }
    38  
    39  // With returns a new [StartOptions] with opts merged on top of o.
    40  func (o startOptions) With(opts ...StartOption) startOptions {
    41  	for _, opt := range opts {
    42  		opt.apply(&o)
    43  	}
    44  	return o
    45  }
    46  
    47  // A StartOption is passed to [Start] to configure a [Handle].
    48  type StartOption interface {
    49  	apply(*startOptions)
    50  }
    51  
    52  // WithClock returns a [StartOption] that configures a [Handle] to use the
    53  // given [clock.Clock] for measuring time.
    54  func WithClock(clk clock.Clock) StartOption {
    55  	return startOptionFunc(func(dst *startOptions) {
    56  		if clk != nil {
    57  			dst.Clock = clk
    58  		}
    59  	})
    60  }
    61  
    62  type startOptionFunc func(*startOptions)
    63  
    64  func (f startOptionFunc) apply(dst *startOptions) {
    65  	f(dst)
    66  }