|
| 1 | +package jsonstream |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "testing" |
| 8 | +) |
| 9 | + |
| 10 | +type Format int |
| 11 | + |
| 12 | +const ( |
| 13 | + FormatJSONLines Format = iota |
| 14 | + FormatJSONArray |
| 15 | +) |
| 16 | + |
| 17 | +var formatNames = map[Format]string{ |
| 18 | + FormatJSONLines: "JSON Lines", |
| 19 | + FormatJSONArray: "JSON Array", |
| 20 | +} |
| 21 | + |
| 22 | +func (f Format) String() string { |
| 23 | + return formatNames[f] |
| 24 | +} |
| 25 | + |
| 26 | +func NewEncoder(out io.Writer, format Format, cfg *Config) Sender { |
| 27 | + switch format { |
| 28 | + case FormatJSONLines: |
| 29 | + return NewJSONLinesEncoderWithConfig(out, cfg) |
| 30 | + case FormatJSONArray: |
| 31 | + return NewJSONArrayEncoderWithConfig(out, cfg) |
| 32 | + default: |
| 33 | + panic(fmt.Errorf("unknown format: %v", format)) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func NewDecoder(in io.Reader, format Format, cfg *Config) Receiver { |
| 38 | + switch format { |
| 39 | + case FormatJSONLines: |
| 40 | + return NewJSONLinesDecoderWithConfig(in, cfg) |
| 41 | + case FormatJSONArray: |
| 42 | + return NewJSONArrayDecoderWithConfig(in, cfg) |
| 43 | + default: |
| 44 | + panic(fmt.Errorf("unknown format: %v", format)) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func BenchmarkEncoder(b *testing.B) { |
| 49 | + for _, c := range configs[1:] { |
| 50 | + for _, f := range []Format{FormatJSONLines, FormatJSONArray} { |
| 51 | + b.Run(c.name+"_"+f.String(), func(b *testing.B) { |
| 52 | + sender := NewEncoder(io.Discard, f, c.config) |
| 53 | + for i := 0; i < b.N; i++ { |
| 54 | + _ = sender.Send(benchSample) |
| 55 | + } |
| 56 | + _ = sender.Done() |
| 57 | + }) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func BenchmarkDecoder(b *testing.B) { |
| 63 | + for _, c := range configs[1:] { |
| 64 | + for _, f := range []Format{FormatJSONLines, FormatJSONArray} { |
| 65 | + b.Run(c.name+"_"+f.String(), func(b *testing.B) { |
| 66 | + input := bytes.NewBuffer(nil) |
| 67 | + sender := NewEncoder(input, f, c.config) |
| 68 | + for i := 0; i < b.N; i++ { |
| 69 | + _ = sender.Send(benchSample) |
| 70 | + } |
| 71 | + _ = sender.Done() |
| 72 | + |
| 73 | + var data Small |
| 74 | + receiver := NewDecoder(input, f, c.config) |
| 75 | + b.ResetTimer() |
| 76 | + for i := 0; i < b.N; i++ { |
| 77 | + _ = receiver.Receive(&data) |
| 78 | + } |
| 79 | + |
| 80 | + }) |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments