github.com/haraldrudell/parl@v0.4.176/pids/pid.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  // Package pids provides a typed process identifier.
     7  package pids
     8  
     9  import (
    10  	"strconv"
    11  
    12  	"github.com/haraldrudell/parl/ints"
    13  	"github.com/haraldrudell/parl/perrors"
    14  	"golang.org/x/exp/constraints"
    15  )
    16  
    17  // Pid is a unique named type for process identifiers
    18  //   - Pid implements [fmt.Stringer]
    19  //   - Pid is [constraints.Ordered]
    20  //   - Pid has [Pid.IsNonZero] [Pid.Int] [Pid.Uint32] methods
    21  type Pid uint32
    22  
    23  // NewPid returns a process identifier based on a 32-bit integer
    24  func NewPid(u32 uint32) (pid Pid) { return Pid(u32) }
    25  
    26  // NewPid1 returns a typed value process identifier panicking on error
    27  func NewPid1[T constraints.Integer](pid T) (typedPid Pid) {
    28  	var err error
    29  	if typedPid, err = ConvertToPid(pid); err != nil {
    30  		panic(err)
    31  	}
    32  	return
    33  }
    34  
    35  // ConvertToPid returns a typed value process identifier from any Integer type
    36  func ConvertToPid[T constraints.Integer](pid T) (typedPid Pid, err error) {
    37  	var u32 uint32
    38  	if u32, err = ints.Unsigned[uint32](pid, perrors.PackFunc()); err != nil {
    39  		return
    40  	}
    41  	typedPid = Pid(u32)
    42  
    43  	return
    44  }
    45  
    46  // IsNonZero returns whether trhe process identifier contains a valid process ID
    47  func (pid Pid) IsNonZero() (isValid bool) { return pid != 0 }
    48  
    49  // Int converts a process identifier to a platform-specific sized int
    50  func (pid Pid) Int() (pidInt int) { return int(pid) }
    51  
    52  // Uint32 converts a process identifier to a 32-bit unsigned integer
    53  func (pid Pid) Uint32() (pidUint32 uint32) { return uint32(pid) }
    54  
    55  func (pid Pid) String() (s string) { return strconv.Itoa(int(pid)) }