Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TransactionBufferReader.h « DuetWiFi « DuetNG « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1fbfb017bce01cafe78a7cb8efc1c4d64014cc98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * TransactionBufferReader.h
 *
 *  Created on: 7 Jul 2016
 *      Author: David
 */

#ifndef SRC_DUETNG_TRANSACTIONBUFFERREADER_H_
#define SRC_DUETNG_TRANSACTIONBUFFERREADER_H_

#include "Core.h"
#include "TransactionBuffer.h"

// Helper class to extract values in sequence from a TransactionBuffer
class TransactionBufferReader
{
public:
	TransactionBufferReader(TransactionBuffer& tb);

	// Read a value of a primitive type
	template<class T> T GetPrimitive();

	// Read an array of primitive types
	template<class T> void GetArray(T * arr, size_t numElems);

	// Read a string
	const char* GetString(size_t fieldWidth);

	// Test whether we ran off the end
	bool IsOk() const { return ok; }

private:
	TransactionBuffer& buf;
	uint32_t offset;
	bool ok;
};

template <class T> T TransactionBufferReader::GetPrimitive()
{
	if (ok)
	{
		if (offset + sizeof(T) <= buf.GetLength())
		{
			T rslt = *reinterpret_cast<const T*>(buf.GetData() + offset);
			offset += sizeof(T);
			return rslt;
		}
		ok = false;
	}
	return static_cast<T>(0);
}

template<class T> void TransactionBufferReader::GetArray(T * arr, size_t numElems)
{
	for (size_t i = 0; i < numElems; ++i)
	{
		arr[i] = GetPrimitive<T>();
	}
}

#endif /* SRC_DUETNG_TRANSACTIONBUFFERREADER_H_ */