예제 #1
0
func TestConversion(t *testing.T) {
	buf := make([]byte, 8)
	message.Uint64ToByteArray(buf, testId)
	id := message.ByteArrayToUint64(buf)
	assert.Equal(t, testId, id, "uint64 conversion is wrong!")

	buf = make([]byte, 4)
	message.Uint32ToByteArray(buf, testNum)
	n := message.ByteArrayToUint32(buf)
	assert.Equal(t, testNum, n, "uint32 conversion is wrong!")

	a1 := message.Uint64ArrayToByteArray(nil)
	a2 := message.Uint64ArrayToByteArray(make([]uint64, 0))
	a3 := message.Uint64ArrayToByteArray(testList)

	assert.Nil(t, a1, "Should return nil with nil as input")
	assert.Len(t, a2, 0, "Should give empty byte list")
	assert.Len(t, a3, len(testList)*8, "One element takes 8 bytes of space")

	l1 := message.ByteArrayToUint64Array(nil)
	l2 := message.ByteArrayToUint64Array(make([]byte, 7))
	l3 := message.ByteArrayToUint64Array(make([]byte, 0))
	l4 := message.ByteArrayToUint64Array(a3)

	assert.Nil(t, l1, "Should return nil with nil as input")
	assert.Nil(t, l2, "Should return nil with incorrect length")
	assert.Len(t, l3, 0, "Should give empty byte list")
	assert.Nil(t, testutils.CompareList(l4, testList), "Lists should be the same")
}
예제 #2
0
/* Given a byte array, add a header containing its length */
func (s *MexSocket) WriteBytes(byteMex []byte) (int, error) {

	if s.IsClosed() {
		return 0, errors.New("Impossible to write on closed socket")
	}

	//convert the size into a byte array
	mexHeader := make([]byte, HEADER_SIZE)
	message.Uint32ToByteArray(mexHeader, uint32(len(byteMex)))

	//compose the full arra to write
	toWrite := append(mexHeader, byteMex...)

	var (
		toWriteLen   = len(toWrite)
		err          error
		totalWritten = 0
		n            int
	)

	//iteratively write all the data, until it's finished or there's an error
	for totalWritten < toWriteLen && err == nil {
		n, err = s.conn.Write(toWrite[totalWritten:])
		totalWritten += n
	}

	// Return the bytes written, any error
	return totalWritten, err
}