예제 #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
/* Reads the header and then all the rest of the packet */
func (s *MexSocket) ReadBytes() ([]byte, int, error) {

	//error if null or empty data
	if s.conn == nil {
		return nil, 0, errors.New("Reader cannot be nil")
	}

	var (
		n                int
		err              error
		totalRead        int
		totalReadHeader  int
		totalReadMessage int
	)

	mexBuffer := make([]byte, HEADER_SIZE)

	//Read the header size
	for totalReadHeader < HEADER_SIZE && err == nil {
		n, err = s.conn.Read(mexBuffer[totalReadHeader:])
		totalReadHeader += n
	}

	//return if error
	if err != nil {
		return nil, totalReadHeader, err
	}

	//convert in integer
	mexSize := int(message.ByteArrayToUint32(mexBuffer))

	mexBuffer = make([]byte, mexSize)

	//Read the header size
	for totalReadMessage < mexSize && err == nil {
		n, err = s.conn.Read(mexBuffer[totalReadMessage:])
		totalReadMessage += n
	}

	totalRead = totalReadMessage + totalReadHeader

	//return if error
	if err != nil {
		return nil, totalRead, err
	}

	return mexBuffer, totalRead, err
}