github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/msgfmt/jsonfmt/level_1/map_test.go (about)

     1  package test
     2  
     3  import (
     4  	"testing"
     5  	"io"
     6  	"github.com/v2pro/plz/msgfmt/jsonfmt"
     7  	"github.com/v2pro/plz/test"
     8  	"github.com/v2pro/plz/countlog"
     9  	"github.com/v2pro/plz/test/must"
    10  	"encoding/json"
    11  	"github.com/v2pro/plz/reflect2"
    12  )
    13  
    14  func Test_map(t *testing.T) {
    15  	t.Run("map int to int", test.Case(func(ctx *countlog.Context) {
    16  		must.JsonEqual(`{
    17  			"1": 1
    18  		}`, jsonfmt.MarshalToString(map[int]int{
    19  			1: 1,
    20  		}))
    21  	}))
    22  	t.Run("map string to int", test.Case(func(ctx *countlog.Context) {
    23  		must.JsonEqual(`{
    24  			"hello": 1
    25  		}`, jsonfmt.MarshalToString(map[string]int{
    26  			"hello": 1,
    27  		}))
    28  	}))
    29  	t.Run("map int to ptr int", test.Case(func(ctx *countlog.Context) {
    30  		one := 1
    31  		must.JsonEqual(`{
    32  			"1": 1
    33  		}`, jsonfmt.MarshalToString(map[int]*int{
    34  			1: &one,
    35  		}))
    36  	}))
    37  	t.Run("map eface to int", test.Case(func(ctx *countlog.Context) {
    38  		must.JsonEqual(`{
    39  			"1": 1
    40  		}`, jsonfmt.MarshalToString(map[interface{}]int{
    41  			1: 1,
    42  		}))
    43  	}))
    44  	t.Run("map int to eface", test.Case(func(ctx *countlog.Context) {
    45  		must.JsonEqual(`{
    46  			"1": 1
    47  		}`, jsonfmt.MarshalToString(map[int]interface{}{
    48  			1: 1,
    49  		}))
    50  	}))
    51  	t.Run("map int to iface", test.Case(func(ctx *countlog.Context) {
    52  		must.JsonEqual(`{
    53  			"1": 1
    54  		}`, jsonfmt.MarshalToString(map[int]io.Closer{
    55  			1: TestCloser(1),
    56  		}))
    57  	}))
    58  	t.Run("map string to eface", test.Case(func(ctx *countlog.Context) {
    59  		must.JsonEqual(`{
    60  			"hello": 1,
    61  			"world": "yes"
    62  		}`, jsonfmt.MarshalToString(map[string]interface{}{
    63  			"hello": 1,
    64  			"world": "yes",
    65  		}))
    66  	}))
    67  }
    68  
    69  func Benchmark_map_unsafe(b *testing.B) {
    70  	encoder := jsonfmt.EncoderOf(reflect2.TypeOf(map[string]int{}))
    71  	m := map[string]int{
    72  		"hello": 1,
    73  		"world": 3,
    74  	}
    75  	b.ReportAllocs()
    76  	b.ResetTimer()
    77  	space := []byte(nil)
    78  	for i := 0; i < b.N; i++ {
    79  		space = encoder.Encode(nil, space[:0], reflect2.PtrOf(m))
    80  	}
    81  }
    82  
    83  func Benchmark_map_safe(b *testing.B) {
    84  	m := map[string]int{
    85  		"hello": 1,
    86  		"world": 3,
    87  	}
    88  	b.ReportAllocs()
    89  	b.ResetTimer()
    90  	for i := 0; i < b.N; i++ {
    91  		json.Marshal(m)
    92  	}
    93  }