github.com/nikandfor/tlog@v0.21.5-0.20231108111739-3ef89426a96d/tlwire/encoder_value_test.go (about)

     1  package tlwire
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/nikandfor/assert"
     7  
     8  	"github.com/nikandfor/tlog/low"
     9  )
    10  
    11  type testEncoder struct {
    12  	N int
    13  }
    14  
    15  func (t testEncoder) TlogAppend(b []byte) []byte {
    16  	return (Encoder{}).AppendInt(b, t.N)
    17  }
    18  
    19  func TestEncoderValueCustomEncoders(t *testing.T) {
    20  	var b low.Buf
    21  	var e Encoder
    22  
    23  	b = e.AppendValue(b[:0], testEncoder{N: 1})
    24  	assert.Equal(t, low.Buf{Int | 1}, b)
    25  
    26  	SetEncoder(testEncoder{}, func(e *Encoder, b []byte, val interface{}) []byte {
    27  		return e.AppendInt(b, val.(testEncoder).N+1)
    28  	})
    29  
    30  	b = e.AppendValue(b[:0], testEncoder{N: 1})
    31  	assert.Equal(t, low.Buf{Int | 2}, b)
    32  
    33  	e.SetEncoder(testEncoder{}, func(e *Encoder, b []byte, val interface{}) []byte {
    34  		return e.AppendInt(b, val.(testEncoder).N+2)
    35  	})
    36  
    37  	b = e.AppendValue(b[:0], testEncoder{N: 1})
    38  	assert.Equal(t, low.Buf{Int | 3}, b)
    39  
    40  	b = (&Encoder{}).AppendValue(b[:0], testEncoder{N: 1})
    41  	assert.Equal(t, low.Buf{Int | 2}, b)
    42  
    43  	SetEncoder(testEncoder{}, nil)
    44  
    45  	b = (&Encoder{}).AppendValue(b[:0], testEncoder{N: 1})
    46  	assert.Equal(t, low.Buf{Int | 1}, b)
    47  }