github.com/anacrolix/torrent@v1.61.0/env.go (about)

     1  package torrent
     2  
     3  import (
     4  	"os"
     5  	"strconv"
     6  
     7  	"github.com/anacrolix/missinggo/v2/panicif"
     8  	"golang.org/x/exp/constraints"
     9  )
    10  
    11  func initIntFromEnv[T constraints.Signed](key string, defaultValue T, bitSize int) T {
    12  	return strconvFromEnv(key, defaultValue, bitSize, strconv.ParseInt)
    13  }
    14  
    15  func initUIntFromEnv[T constraints.Unsigned](key string, defaultValue T, bitSize int) T {
    16  	return strconvFromEnv(key, defaultValue, bitSize, strconv.ParseUint)
    17  }
    18  
    19  func strconvFromEnv[T, U constraints.Integer](key string, defaultValue T, bitSize int, conv func(s string, base, bitSize int) (U, error)) T {
    20  	s := os.Getenv(key)
    21  	if s == "" {
    22  		return defaultValue
    23  	}
    24  	i64, err := conv(s, 10, bitSize)
    25  	panicif.Err(err)
    26  	return T(i64)
    27  }