Improved container support

This commit is contained in:
2019-12-14 00:56:01 +01:00
parent 35cd2873cd
commit 42ca9fefff
3 changed files with 67 additions and 9 deletions

View File

@@ -47,6 +47,8 @@ namespace io {
return value;
}
template <typename T> requires std::is_convertible_v<std::string, T>
T read(std::istream& is, size_t length) {
std::vector<char> t(length);
@@ -62,14 +64,13 @@ namespace io {
return read<T>(is, length);
}
// @todo We need to support std::array
// Extra concept that checks if the size is static
template <Container T>
T read(std::istream& is, size_t length) {
// @todo Properly constuct the container
T v(length);
for (size_t i = 0; i < length; ++i) {
v[i] = io::read<typename T::value_type>(is);
for (auto& e : v) {
e = io::read<typename T::value_type>(is);
}
return v;
}
@@ -79,4 +80,14 @@ namespace io {
size_t length = io::read<size_t>(is);
return read<T>(is, length);
}
// Static sized container
template <Container T> requires requires (T a) { std::tuple_size<T>::value; }
T read(std::istream& is) {
T v;
for (size_t i = 0; i < std::tuple_size<T>::value; ++i) {
v[i] = io::read<typename T::value_type>(is);
}
return v;
}
}

View File

@@ -2,6 +2,7 @@
#include "helper.h"
#include <iostream>
#include <cstdint>
#include <tuple>
namespace io {
// This exists to allow for specialization and clearer errors
@@ -59,6 +60,7 @@ namespace io {
os << s;
}
// @todo Merge this into one function with the proper default automatically
template <Container T>
void write(std::ostream& os, T value, bool store_length = true) {
if (store_length) {
@@ -68,4 +70,14 @@ namespace io {
write<typename T::value_type>(os, entry);
}
}
template <Container T> requires requires (T a) { std::tuple_size<T>::value; }
void write(std::ostream& os, T value, bool store_length = false) {
if (store_length) {
write<size_t>(os, value.size());
}
for (const auto& entry : value) {
write<typename T::value_type>(os, entry);
}
}
}