hack_test.go 929 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package cast
  2. import (
  3. "reflect"
  4. "strings"
  5. "testing"
  6. )
  7. func TestString2bytes(t *testing.T) {
  8. type args struct {
  9. str string
  10. }
  11. tests := []struct {
  12. name string
  13. args args
  14. want []byte
  15. }{
  16. {
  17. name: "common",
  18. args: args{
  19. str: "abc",
  20. },
  21. want: []byte{'a', 'b', 'c'},
  22. },
  23. {
  24. name: "nil",
  25. args: args{
  26. str: "",
  27. },
  28. want: nil,
  29. },
  30. }
  31. for _, tt := range tests {
  32. t.Run(tt.name, func(t *testing.T) {
  33. if got := StringToBytes(tt.args.str); !reflect.DeepEqual(got, tt.want) {
  34. t.Errorf("StringToBytes() = %v, want %v", got, tt.want)
  35. }
  36. })
  37. }
  38. }
  39. var (
  40. l = 1024 * 1024
  41. str = strings.Repeat("a", l)
  42. )
  43. func BenchmarkStringToBytes(b *testing.B) {
  44. for i := 0; i < b.N; i++ {
  45. bt := []byte(str)
  46. if len(bt) != l {
  47. b.Fatal()
  48. }
  49. }
  50. }
  51. func BenchmarkStringToBytesUnsafe(b *testing.B) {
  52. for i := 0; i < b.N; i++ {
  53. bt := StringToBytes(str)
  54. if len(bt) != l {
  55. b.Fatal()
  56. }
  57. }
  58. }