TinyRobotics
Loading...
Searching...
No Matches
Serializable.h
1#pragma once
2#include "Stream.h"
3#include "TinyRobotics/utils/Config.h"
4
5namespace tinyrobotics {
6
7// Reads a line from the stream into a std::stream. Returns true if a line was
8// read, false on EOF.
9bool readLine(Stream& s, std::string& out) {
10 out.clear();
11 while (true) {
12 int c = s.read();
13 if (c < 0) {
14 // If nothing read, return false to signal EOF
15 return !out.empty();
16 }
17 if (c == '\n') break;
18 out += static_cast<char>(c);
19 }
20 return true;
21}
22
23/**
24 * @brief This class defines an interface for serializable objects that can be
25 * converted to and from a string representation. It provides two pure virtual
26 * methods: toString() for converting the object to a string, and fromString()
27 * for populating the object from a string input. This interface can be
28 * implemented by any class that needs to support serialization and
29 * deserialization, allowing for easy storage, transmission, or logging of
30 * object state in a human-readable
31 */
32class Serializable {
33 public:
34 virtual std::string toString() const = 0;
35 const char* toCString() const { return toString().c_str(); }
36 virtual bool fromString(const std::string& in) = 0;
37 virtual bool fromString(const char* in) {
38 return fromString(std::string(in));
39 }
40 size_t writeTo(Print& out) const { return out.println(toCString()); }
41 size_t readFrom(Stream& in) {
42 std::string inStr;
43 if (!readLine(in, inStr)) return 0;
44 return fromString(inStr.c_str()) ? inStr.length() + 1 : 0;
45 }
46};
47
48} // namespace tinyrobotics
This class defines an interface for serializable objects that can be converted to and from a string r...
Definition: Serializable.h:32