hex_test.mx raw

   1  package hex
   2  
   3  import "testing"
   4  
   5  func TestEncDec(t *testing.T) {
   6  	if got := Enc([]byte{0xde, 0xad, 0xbe, 0xef}); got != "deadbeef" {
   7  		t.Fatal("Enc: got " | got)
   8  	}
   9  	b, err := Dec("deadbeef")
  10  	if err != nil {
  11  		t.Fatal(err)
  12  	}
  13  	if string(b) != string([]byte{0xde, 0xad, 0xbe, 0xef}) {
  14  		t.Fatal("Dec: got " | string(b))
  15  	}
  16  	if _, err = Dec("nothex"); err == nil {
  17  		t.Fatal("Dec of non-hex should fail")
  18  	}
  19  	if DecLen(8) != 4 {
  20  		t.Fatal("DecLen(8) != 4")
  21  	}
  22  }
  23  
  24  func TestEncBytesDecBytes(t *testing.T) {
  25  	dst := []byte{:4}
  26  	n := EncBytes(dst, []byte{0x01, 0xff})
  27  	if n != 4 || string(dst) != "01ff" {
  28  		t.Fatal("EncBytes: got " | string(dst))
  29  	}
  30  	back := []byte{:2}
  31  	n, err := DecBytes(back, []byte("01ff"))
  32  	if err != nil {
  33  		t.Fatal(err)
  34  	}
  35  	if n != 2 || string(back) != string([]byte{0x01, 0xff}) {
  36  		t.Fatal("DecBytes: got " | string(back))
  37  	}
  38  }
  39  
  40  // TestAppend covers the tail-write helpers: Moxie subslices are copies, so a
  41  // helper that encodes into dst[len(dst):] only works if it writes through the
  42  // parent slice.
  43  func TestAppend(t *testing.T) {
  44  	buf := EncAppend([]byte("k="), []byte{0x0a, 0xb1})
  45  	if string(buf) != "k=0ab1" {
  46  		t.Fatal("EncAppend: got " | string(buf))
  47  	}
  48  	buf = EncAppend(buf, []byte{0x00})
  49  	if string(buf) != "k=0ab100" {
  50  		t.Fatal("EncAppend twice: got " | string(buf))
  51  	}
  52  	dec, err := DecAppend(nil, []byte("0ab1"))
  53  	if err != nil {
  54  		t.Fatal(err)
  55  	}
  56  	if string(dec) != string([]byte{0x0a, 0xb1}) {
  57  		t.Fatal("DecAppend: got " | string(dec))
  58  	}
  59  	dec, err = DecAppend(dec, []byte("00"))
  60  	if err != nil {
  61  		t.Fatal(err)
  62  	}
  63  	if string(dec) != string([]byte{0x0a, 0xb1, 0x00}) {
  64  		t.Fatal("DecAppend twice: got " | string(dec))
  65  	}
  66  	// DecAppend has nothing to decode from a single byte.
  67  	if _, err = DecAppend(nil, []byte("a")); err == nil {
  68  		t.Fatal("DecAppend of one byte should fail")
  69  	}
  70  }
  71