Beispiel #1
0
// Read reads a series of bytes from the stream. This method may block the
// calling application for an arbitrary amount of time.
// Errors are not guaranteed to be reported synchronously with the call, but may
// instead be delayed until a subsequent call.
// This function is equivalent to the libvirt function "Recv" but it has been
// renamed to "Read" in order to implement the standard interface io.Reader. And
// due to that interface requirement, this function now returns (0, io.EOF)
// instead of (0, nil) when there's nothing left to be read from the stream.
func (str Stream) Read(data []byte) (int, error) {
	dataLen := len(data)

	cData := (*C.char)(C.malloc(C.size_t(dataLen)))
	defer C.free(unsafe.Pointer(cData))

	str.log.Printf("receiving %v bytes from stream...\n", dataLen)
	cRet := C.virStreamRecv(str.virStream, (*C.char)(unsafe.Pointer(cData)), C.size_t(dataLen))
	ret := int32(cRet)

	if ret < 0 {
		err := LastError()
		str.log.Printf("an error occurred: %v\n", err)
		return 0, err
	}

	str.log.Printf("%v bytes received\n", ret)

	if ret == 0 && dataLen > 0 {
		return 0, io.EOF
	}

	newData := C.GoStringN(cData, cRet)
	copy(data, newData)

	return int(ret), nil
}
Beispiel #2
0
func (v *VirStream) Read(p []byte) (int, error) {
	n := C.virStreamRecv(v.ptr, (*C.char)(unsafe.Pointer(&p[0])), C.size_t(len(p)))
	if n < 0 {
		return 0, GetLastError()
	}
	if n == 0 {
		return 0, io.EOF
	}

	return int(n), nil
}