util.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Package util provides auxiliary functions internally used in webrtc package
  2. package util
  3. import (
  4. "errors"
  5. "strings"
  6. "github.com/pion/randutil"
  7. )
  8. const (
  9. runesAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10. )
  11. // Use global random generator to properly seed by crypto grade random.
  12. var globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals
  13. // MathRandAlpha generates a mathmatical random alphabet sequence of the requested length.
  14. func MathRandAlpha(n int) string {
  15. return globalMathRandomGenerator.GenerateString(n, runesAlpha)
  16. }
  17. // RandUint32 generates a mathmatical random uint32.
  18. func RandUint32() uint32 {
  19. return globalMathRandomGenerator.Uint32()
  20. }
  21. // FlattenErrs flattens multiple errors into one
  22. func FlattenErrs(errs []error) error {
  23. errs2 := []error{}
  24. for _, e := range errs {
  25. if e != nil {
  26. errs2 = append(errs2, e)
  27. }
  28. }
  29. if len(errs2) == 0 {
  30. return nil
  31. }
  32. return multiError(errs2)
  33. }
  34. type multiError []error //nolint:errname
  35. func (me multiError) Error() string {
  36. var errstrings []string
  37. for _, err := range me {
  38. if err != nil {
  39. errstrings = append(errstrings, err.Error())
  40. }
  41. }
  42. if len(errstrings) == 0 {
  43. return "multiError must contain multiple error but is empty"
  44. }
  45. return strings.Join(errstrings, "\n")
  46. }
  47. func (me multiError) Is(err error) bool {
  48. for _, e := range me {
  49. if errors.Is(e, err) {
  50. return true
  51. }
  52. if me2, ok := e.(multiError); ok { //nolint:errorlint
  53. if me2.Is(err) {
  54. return true
  55. }
  56. }
  57. }
  58. return false
  59. }