github.com/haraldrudell/parl@v0.4.176/idempotent-close.go (about) 1 /* 2 © 2024–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package parl 7 8 import ( 9 "io" 10 "sync/atomic" 11 ) 12 13 type IdempotentCloser[C io.Closer] struct { 14 closer io.Closer 15 isClose atomic.Bool 16 } 17 18 func NewIdemPotentCloser[C io.Closer](closer C) (idempotentCloser *IdempotentCloser[C]) { 19 return &IdempotentCloser[C]{closer: closer} 20 } 21 22 func (c *IdempotentCloser[C]) Close() (err error) { 23 if c.isClose.Load() || !c.isClose.CompareAndSwap(false, true) { 24 return 25 } else if c.closer == nil { 26 return 27 } 28 err = c.closer.Close() 29 return 30 } 31 32 func (c *IdempotentCloser[C]) IsClose() (isClose bool) { return c.isClose.Load() }