#pragma once #include // --------- ˽ÓÐ/ÄÚ²¿£º¶Áд¹¤¾ß --------- namespace SERVO { template inline void write_pod(std::ostream& os, const T& v) { os.write(reinterpret_cast(&v), sizeof(T)); } template inline bool read_pod(std::istream& is, T& v) { return bool(is.read(reinterpret_cast(&v), sizeof(T))); } inline void write_string(std::ostream& os, const std::string& s) { uint32_t n = static_cast(s.size()); write_pod(os, n); if (n) os.write(s.data(), n); } inline bool read_string(std::istream& is, std::string& s) { uint32_t n = 0; if (!read_pod(is, n)) return false; s.resize(n); if (n) return bool(is.read(&s[0], n)); return true; } template inline void write_vec(std::ostream& os, const std::vector& v) { uint32_t n = static_cast(v.size()); write_pod(os, n); if (n) os.write(reinterpret_cast(v.data()), sizeof(T) * n); } template inline bool read_vec(std::istream& is, std::vector& v) { uint32_t n = 0; if (!read_pod(is, n)) return false; v.resize(n); if (n) return bool(is.read(reinterpret_cast(v.data()), sizeof(T) * n)); return true; } // vector ÌØ»¯Ð´¶Á inline void write_vec_str(std::ostream& os, const std::vector& v) { uint32_t n = static_cast(v.size()); write_pod(os, n); for (const auto& s : v) write_string(os, s); } inline bool read_vec_str(std::istream& is, std::vector& v) { uint32_t n = 0; if (!read_pod(is, n)) return false; v.clear(); v.reserve(n); for (uint32_t i = 0; i < n; ++i) { std::string s; if (!read_string(is, s)) return false; v.emplace_back(std::move(s)); } return true; } // optional ¡ú bool + int64 (ms since epoch) inline void write_opt_time(std::ostream& os, const std::optional& tp) { uint8_t has = tp.has_value() ? 1 : 0; write_pod(os, has); if (has) { auto ms = std::chrono::duration_cast(tp->time_since_epoch()).count(); int64_t v = static_cast(ms); write_pod(os, v); } } inline bool read_opt_time(std::istream& is, std::optional& tp) { uint8_t has = 0; if (!read_pod(is, has)) return false; if (!has) { tp.reset(); return true; } int64_t v = 0; if (!read_pod(is, v)) return false; tp = std::chrono::system_clock::time_point(std::chrono::milliseconds(v)); return true; } }