github.com/haraldrudell/parl@v0.4.176/iana/port.go (about) 1 /* 2 © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package iana 7 8 import ( 9 "strconv" 10 11 "github.com/haraldrudell/parl/ints" 12 "github.com/haraldrudell/parl/perrors" 13 "golang.org/x/exp/constraints" 14 ) 15 16 // Port contains an iana port number 1…65535. 17 // - Port is ordered 18 // - Port implements fmt.Stringer 19 // - Port has IsValid, Int and Uint16 methods 20 type Port uint16 21 22 // NewPort returns iana.Port for any integer value. 23 // - values larger that 65535 produce error testable with errors.Is(err, ints.ErrTooLarge) 24 // - port may be invalid, ie. not an iana-assigned value, check with port.IsValid 25 // - or use NewValidPort 26 func NewPort[T constraints.Integer](integer T) (port Port, err error) { 27 28 // convert to uint16 29 var u16 uint16 30 if u16, err = ints.Unsigned[uint16](integer, perrors.PackFunc()); err != nil { 31 return 32 } 33 34 // convert to iana.Port 35 port = Port(u16) 36 37 return 38 } 39 40 // NewValidPort returns iana.Port for any integer value. 41 // - values larger that 65535 produce error testable with errors.Is(err, ints.ErrTooLarge) 42 // - port is valid 43 func NewValidPort[T constraints.Integer](integer T) (port Port, err error) { 44 if port, err = NewPort(integer); err != nil { 45 return 46 } 47 if !port.IsValid() { 48 err = perrors.ErrorfPF("invalid port value: %d", port) 49 return 50 } 51 52 return 53 } 54 55 // NewPort1 returns iana.Port for any integer value. 56 // - if value is too large, panic 57 // - port may be invalid, ie. not an iana-allowed value, check with port.IsValid 58 // - or use NewValidPort 59 func NewPort1[T constraints.Integer](integer T) (port Port) { 60 var err error 61 if port, err = NewPort(integer); err != nil { 62 panic(err) 63 } 64 return 65 } 66 67 func (port Port) IsValid() (isValid bool) { 68 return port != 0 69 } 70 71 func (port Port) Uint16() (portUint16 uint16) { 72 return uint16(port) 73 } 74 75 func (port Port) Int() (portInt int) { 76 return int(port) 77 } 78 79 func (port Port) String() (numericString string) { 80 return strconv.Itoa(int(port)) 81 }