DataBlock.h 2.68 KB
/*
 * producer.h
 *
 *  Created on: 15 gru 2018
 *      Author: mariuszo
 */

#ifndef DATABLOCK_H_
#define DATABLOCK_H_

#include <assert.h>
#include <atomic>
#include "enums.h"
/*
#include <unistd.h>
*/
class SubsystemBase;

enum class block_type : off_t {
	block_torelease=-1,
	block_empty=-2
};

struct  dataSlot {
	std::atomic<off_t> dataSlotID;
	off_t dataAddr;
	size_t dataSize;
};

class DataBlock {
	void* m_address;
	dataSlot* m_dataSlot;
	off_t m_syncSlotID;
	SubsystemBase* m_attachedTo;
public:
	DataBlock(const DataBlock& data):m_address(data.m_address), m_dataSlot(data.m_dataSlot), m_syncSlotID(data.m_syncSlotID), m_attachedTo(NULL) {}
	DataBlock(const specialid_type& type=specialid_type::specialid_empty):m_address(NULL), m_dataSlot(NULL), m_syncSlotID(static_cast<off_t>(type)), m_attachedTo(NULL) {}
	DataBlock(dataSlot& data, const void* baseAddress, const off_t& slotID=static_cast<off_t>(specialid_type::specialid_none)):m_address((baseAddress)?(uint8_t*)baseAddress+data.dataAddr:NULL), m_dataSlot(&data), m_syncSlotID(slotID), m_attachedTo(NULL){}
	virtual ~DataBlock();

	void setType(const specialid_type& type){
		m_address=m_dataSlot=NULL;
		m_syncSlotID=static_cast<off_t>(type);
	}
	void setEmpty(){
		m_address=m_dataSlot=NULL;
		m_syncSlotID=static_cast<off_t>(specialid_type::specialid_empty);
	}
	void setStop(){
		m_address=m_dataSlot=NULL;
		m_syncSlotID=static_cast<off_t>(specialid_type::specialid_stop);
	}
	void setTimeout(){
		m_address=m_dataSlot=NULL;
		m_syncSlotID=static_cast<off_t>(specialid_type::specialid_timeout);
	}
	const void* operator *() const {
		return m_address;
	}
	const size_t size() const {
		if (m_dataSlot)
			return m_dataSlot->dataSize;
		else
			return 0;
	}
	const off_t blockID() const {
		assert(m_dataSlot && m_dataSlot->m_blockID>=0);
		return m_dataSlot->dataSlotID.load(std::memory_order_acquire);
	}
	const off_t& syncSlotID() const {
		return m_syncSlotID;
	}
	bool operator !() const {
		return m_address==NULL || !m_dataSlot || m_dataSlot->dataSlotID<0;
	}

	operator bool () const {
		return !!(*this);
	}

	bool isType(const specialid_type& type) const {
		return m_syncSlotID==static_cast<off_t>(type);
	}
	bool isEmpty() const {
		return m_syncSlotID==static_cast<off_t>(specialid_type::specialid_empty);
	}
	bool isStop() const {
		return m_syncSlotID==static_cast<off_t>(specialid_type::specialid_stop);
	}
	bool isTimeout() const {
		return m_syncSlotID==static_cast<off_t>(specialid_type::specialid_timeout);
	}
	bool isOutOfMemory() const {
		return m_syncSlotID==static_cast<off_t>(specialid_type::specialid_outofmemory);
	}
	void attach(SubsystemBase* attachedTo) {m_attachedTo=attachedTo;}
	void detach() {m_attachedTo=NULL;}
};

#endif /* DATABLOCK_H_ */