binary_test.go raw

   1  package event
   2  
   3  import (
   4  	"bufio"
   5  	"bytes"
   6  	"testing"
   7  	"time"
   8  
   9  	"next.orly.dev/pkg/nostr/encoders/event/examples"
  10  	"next.orly.dev/pkg/nostr/utils"
  11  	"next.orly.dev/pkg/lol/chk"
  12  )
  13  
  14  func TestTMarshalBinary_UnmarshalBinary(t *testing.T) {
  15  	scanner := bufio.NewScanner(bytes.NewBuffer(examples.Cache))
  16  	scanner.Buffer(make([]byte, 0, 1_000_000_000), 1_000_000_000)
  17  	var rem, out []byte
  18  	var err error
  19  	now := time.Now()
  20  	var counter int
  21  	for scanner.Scan() {
  22  		// Create new event objects and buffer for each iteration
  23  		buf := new(bytes.Buffer)
  24  		ea, eb := New(), New()
  25  
  26  		chk.E(scanner.Err())
  27  		b := scanner.Bytes()
  28  		c := make([]byte, 0, len(b))
  29  		c = append(c, b...)
  30  		if rem, err = ea.Unmarshal(c); chk.E(err) {
  31  			t.Fatal(err)
  32  		}
  33  		if len(rem) != 0 {
  34  			t.Fatalf(
  35  				"some of input remaining after marshal/unmarshal: '%s'",
  36  				rem,
  37  			)
  38  		}
  39  		// Reset buffer before marshaling
  40  		buf.Reset()
  41  		ea.MarshalBinary(buf)
  42  
  43  		// Create a new buffer for unmarshaling
  44  		buf2 := bytes.NewBuffer(buf.Bytes())
  45  		if err = eb.UnmarshalBinary(buf2); chk.E(err) {
  46  			t.Fatal(err)
  47  		}
  48  
  49  		// Marshal unmarshaled binary event back to JSON
  50  		unmarshaledJSON := eb.Serialize()
  51  		defer func(ev *E) {
  52  			eb.Free()
  53  		}(eb)
  54  
  55  		// Compare the two JSON representations
  56  		if !utils.FastEqual(b, unmarshaledJSON) {
  57  			t.Fatalf(
  58  				"JSON representations don't match after binary marshaling/unmarshaling:\nOriginal: %s\nUnmarshaled: %s",
  59  				b, unmarshaledJSON,
  60  			)
  61  		}
  62  
  63  		counter++
  64  		out = out[:0]
  65  	}
  66  	chk.E(scanner.Err())
  67  	t.Logf(
  68  		"unmarshaled json, marshaled binary, unmarshaled binary, %d events in %v av %v per event",
  69  		counter, time.Since(now), time.Since(now)/time.Duration(counter),
  70  	)
  71  }
  72