master
go 96 lines 2.13 KB
Raw
1 package testutils
2
3 import (
4 "bufio"
5 "fmt"
6 "net"
7 "net/netip"
8 "net/url"
9 "strings"
10 "sync"
11
12 "github.com/multiformats/go-multiaddr"
13 manet "github.com/multiformats/go-multiaddr/net"
14 )
15
16 var (
17 AlphabetEasy = []rune("abcdefghijklmnopqrstuvwxyz01234567890-_")
18 AlphabetHard = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-_+= ;.,<>'\"[]{}() ")
19 )
20
21 // StrCat takes a bunch of strings or string slices
22 // and concats them all together into one string slice.
23 // If an arg is not one of those types, this panics.
24 // If an arg is an empty string, it is dropped.
25 func StrCat(args ...any) []string {
26 res := make([]string, 0)
27 for _, a := range args {
28 if s, ok := a.(string); ok {
29 if s != "" {
30 res = append(res, s)
31 }
32 continue
33 }
34 if ss, ok := a.([]string); ok {
35 for _, s := range ss {
36 if s != "" {
37 res = append(res, s)
38 }
39 }
40 continue
41 }
42 panic(fmt.Sprintf("arg '%v' must be a string or string slice, but is '%T'", a, a))
43 }
44 return res
45 }
46
47 // PreviewStr returns a preview of s, which is a prefix for logging that avoids dumping a huge string to logs.
48 func PreviewStr(s string) string {
49 suffix := "..."
50 previewLength := 10
51 if len(s) < previewLength {
52 previewLength = len(s)
53 suffix = ""
54 }
55 return s[0:previewLength] + suffix
56 }
57
58 func SplitLines(s string) []string {
59 var lines []string
60 scanner := bufio.NewScanner(strings.NewReader(s))
61 for scanner.Scan() {
62 lines = append(lines, scanner.Text())
63 }
64 return lines
65 }
66
67 // URLStrToMultiaddr converts a URL string like http://localhost:80 to a multiaddr.
68 func URLStrToMultiaddr(u string) multiaddr.Multiaddr {
69 parsedURL, err := url.Parse(u)
70 if err != nil {
71 panic(err)
72 }
73 addrPort, err := netip.ParseAddrPort(parsedURL.Host)
74 if err != nil {
75 panic(err)
76 }
77 tcpAddr := net.TCPAddrFromAddrPort(addrPort)
78 ma, err := manet.FromNetAddr(tcpAddr)
79 if err != nil {
80 panic(err)
81 }
82 return ma
83 }
84
85 // ForEachPar invokes f in a new goroutine for each element of s and waits for all to complete.
86 func ForEachPar[T any](s []T, f func(T)) {
87 wg := sync.WaitGroup{}
88 wg.Add(len(s))
89 for _, x := range s {
90 go func(x T) {
91 defer wg.Done()
92 f(x)
93 }(x)
94 }
95 wg.Wait()
96 }