util.go 1.6 KB

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