github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/iokit/misc.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package iokit
     7  
     8  import "io"
     9  
    10  func SafeCloseWithDefault(c io.Closer, nilErrorFn func() error) error {
    11  	switch {
    12  	case c != nil:
    13  		return c.Close()
    14  	case nilErrorFn == nil:
    15  		return nil
    16  	default:
    17  		return nilErrorFn()
    18  	}
    19  }
    20  
    21  func SafeClose(c io.Closer) error {
    22  	return SafeCloseWithDefault(c, nil)
    23  }
    24  
    25  func SafeCloseChain(c io.Closer, prev error) error {
    26  	if c != nil {
    27  		err := c.Close()
    28  		if prev == nil {
    29  			return err
    30  		}
    31  	}
    32  	return prev
    33  }