Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ca-io.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
52#ifndef CA_IO_H
53#define CA_IO_H
54
55#include <algorithm>
56#include <array>
57#include <cctype>
58#include <concepts>
59#include <cstdint>
60#include <iomanip>
61#include <istream>
62#include <limits>
63#include <ostream>
64#include <sstream>
65#include <string>
66#include <type_traits>
67#include <utility>
68
69#include <ah-cpp-compat.H>
70#include <ah-errors.H>
71#include <tpl_array.H>
72
73#include <ca-traits.H>
74#include <tpl_ca_concepts.H>
75
76namespace Aleph {
77namespace CA {
78
84struct RGB8
85{
86 std::uint8_t r = 0;
87 std::uint8_t g = 0;
88 std::uint8_t b = 0;
89
90 friend constexpr bool operator == (RGB8, RGB8) noexcept = default;
91};
92
114
117
126template <typename T>
128{
132
142 [[nodiscard]] T at(ca_size_t row, ca_size_t col) const
143 {
145 << "Grid_Snapshot::at: coordinate (" << row << ", " << col << ") out of " << height << "x"
146 << width;
147 return cells[row * width + col];
148 }
149};
150
159{
160 std::string rule = "B3/S23";
161 std::string name;
162 std::string comment;
163 bool trim_dead_border = false;
164 std::size_t line_width = 70;
165};
166
173{
174 char alive = 'O';
175 char dead = '.';
176 std::string comment;
177};
178
185{
186 char delimiter = ',';
187 bool skip_empty_lines = true;
188};
189
196{
197 bool pretty = false;
198 std::string rule;
199};
200
207{
208 std::uint16_t max_value = 255;
209};
210
219template <typename State>
221{
222 State dead{};
223 std::uint8_t dead_value = 255;
224 std::uint8_t alive_value = 0;
225
230 [[nodiscard]] std::uint8_t operator () (const State &v) const
231 {
232 return v == dead ? dead_value : alive_value;
233 }
234};
235
243template <typename State>
245{
246 State dead{};
247 RGB8 dead_colour{255, 255, 255};
249
254 [[nodiscard]] RGB8 operator () (const State &v) const
255 {
256 return v == dead ? dead_colour : alive_colour;
257 }
258};
259
260namespace ca_io_detail {
261
262template <typename Lattice>
263inline void require_rank2(const char *fn)
264{
265 static_assert(LatticeLike<Lattice>, "CA IO requires a LatticeLike frame");
266 static_assert(Lattice::rank == 2, "CA IO currently supports 2D frames");
267 (void) fn;
268}
269
270inline std::string trim_copy(const std::string &s)
271{
272 std::size_t b = 0;
273 while (b < s.size() and std::isspace(static_cast<unsigned char>(s[b])))
274 ++b;
275 std::size_t e = s.size();
276 while (e > b and std::isspace(static_cast<unsigned char>(s[e - 1])))
277 --e;
278 return s.substr(b, e - b);
279}
280
281inline std::string lower_copy(std::string s)
282{
283 for (char &c : s)
284 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
285 return s;
286}
287
288inline bool blank(const std::string &s)
289{
290 for (const char c : s)
291 if (not std::isspace(static_cast<unsigned char>(c)))
292 return false;
293 return true;
294}
295
296inline ca_size_t parse_size_token(const std::string &s, const char *what)
297{
298 const std::string t = trim_copy(s);
299 ah_domain_error_if(t.empty()) << what << ": empty size";
300 ca_size_t value = 0;
301 for (const char c : t)
302 {
303 ah_domain_error_if(not std::isdigit(static_cast<unsigned char>(c)))
304 << what << ": invalid unsigned size '" << s << "'";
305 const ca_size_t digit = static_cast<ca_size_t>(c - '0');
306 ah_overflow_error_if(value > (std::numeric_limits<ca_size_t>::max() - digit) / 10)
307 << what << ": size overflows ca_size_t";
308 value = value * 10 + digit;
309 }
310 return value;
311}
312
313inline ca_index_t parse_index_token(const std::string &s, const char *what)
314{
315 const std::string t = trim_copy(s);
316 ah_domain_error_if(t.empty()) << what << ": empty coordinate";
317 std::size_t i = 0;
318 bool neg = false;
319 if (t[i] == '-' or t[i] == '+')
320 {
321 neg = t[i] == '-';
322 ++i;
323 }
324 ah_domain_error_if(i == t.size()) << what << ": missing coordinate digits";
325 ca_index_t value = 0;
326 for (; i < t.size(); ++i)
327 {
328 const char c = t[i];
329 ah_domain_error_if(not std::isdigit(static_cast<unsigned char>(c)))
330 << what << ": invalid coordinate '" << s << "'";
331 const ca_index_t digit = static_cast<ca_index_t>(c - '0');
332 ah_overflow_error_if(value > (std::numeric_limits<ca_index_t>::max() - digit) / 10)
333 << what << ": coordinate overflows ca_index_t";
334 value = value * 10 + digit;
335 }
336 return neg ? -value : value;
337}
338
340inline constexpr ca_index_t Max_Coordinate = std::numeric_limits<ca_index_t>::max();
341
344inline constexpr ca_size_t Max_Pattern_Extent = static_cast<ca_size_t>(Max_Coordinate) + 1;
345
347inline ca_index_t checked_coord_add(const ca_index_t a, const ca_index_t b, const char *what)
348{
349 ah_overflow_error_if((b > 0 and a > std::numeric_limits<ca_index_t>::max() - b) or
350 (b < 0 and a < std::numeric_limits<ca_index_t>::min() - b))
351 << what << ": coordinate overflows ca_index_t";
352 return a + b;
353}
354
355inline Array<std::string> split_comment_lines(const std::string &comment)
356{
357 Array<std::string> lines;
358 std::istringstream in(comment);
359 std::string line;
360 while (std::getline(in, line))
361 lines.append(line);
362 if (comment.empty())
363 lines.clear();
364 return lines;
365}
366
367inline std::string json_escape(const std::string &s)
368{
369 std::ostringstream out;
370 for (const char c : s)
371 {
372 switch (c)
373 {
374 case '"':
375 out << "\\\"";
376 break;
377 case '\\':
378 out << "\\\\";
379 break;
380 case '\n':
381 out << "\\n";
382 break;
383 case '\r':
384 out << "\\r";
385 break;
386 case '\t':
387 out << "\\t";
388 break;
389 default:
390 if (static_cast<unsigned char>(c) < 0x20)
391 out << "\\u" << std::hex << std::setw(4) << std::setfill('0')
392 << static_cast<unsigned>(static_cast<unsigned char>(c)) << std::dec
393 << std::setfill(' ');
394 else
395 out << c;
396 break;
397 }
398 }
399 return out.str();
400}
401
402inline std::string rle_token(ca_size_t n, char glyph)
403{
404 if (n == 0)
405 return {};
406 std::string token;
407 if (n != 1)
408 token = std::to_string(n);
409 token.push_back(glyph);
410 return token;
411}
412
413inline void append_rle_token(std::string &body, ca_size_t n, char glyph)
414{
415 body += rle_token(n, glyph);
416}
417
418inline void write_wrapped_rle_body(std::ostream &out,
419 const std::string &body,
420 const std::size_t line_width)
421{
422 std::size_t col = 0;
423 std::size_t pos = 0;
424 const std::size_t width = line_width == 0 ? std::numeric_limits<std::size_t>::max() : line_width;
425 while (pos < body.size())
426 {
427 const std::size_t start = pos;
428 while (pos < body.size() and std::isdigit(static_cast<unsigned char>(body[pos])))
429 ++pos;
430 ah_domain_error_if(pos == body.size()) << "write_rle: malformed body token";
431 ++pos;
432 const std::size_t len = pos - start;
433 if (col != 0 and col + len > width)
434 {
435 out << '\n';
436 col = 0;
437 }
438 out.write(body.data() + static_cast<std::ptrdiff_t>(start), static_cast<std::streamsize>(len));
439 col += len;
440 if (body[pos - 1] == '!')
441 {
442 out << '\n';
443 col = 0;
444 }
445 }
446 if (col != 0)
447 out << '\n';
448}
449
450inline std::string header_value(const std::string &line, const std::string &key)
451{
452 std::istringstream parts(line);
453 std::string part;
454 while (std::getline(parts, part, ','))
455 {
456 const auto eq = part.find('=');
457 if (eq == std::string::npos)
458 continue;
459 const std::string lhs = lower_copy(trim_copy(part.substr(0, eq)));
460 if (lhs == key)
461 return trim_copy(part.substr(eq + 1));
462 }
463 return {};
464}
465
467 const Array<Coord_Vec<2>> &absolute,
468 const bool have_extent,
469 const ca_index_t min_row,
470 const ca_index_t min_col,
471 const ca_index_t max_row,
472 const ca_index_t max_col,
473 const char *what)
474{
475 if (not have_extent)
476 {
477 pattern.width = 0;
478 pattern.height = 0;
479 pattern.origin_row = 0;
480 pattern.origin_col = 0;
481 pattern.alive.clear();
482 return;
483 }
484
485 // max - min may not fit in ca_index_t, but it does in ca_size_t
486 const ca_size_t row_span = static_cast<ca_size_t>(max_row) - static_cast<ca_size_t>(min_row);
487 const ca_size_t col_span = static_cast<ca_size_t>(max_col) - static_cast<ca_size_t>(min_col);
489 << what << ": pattern extent needs coordinates beyond ca_index_t";
490
491 pattern.origin_row = min_row;
492 pattern.origin_col = min_col;
493 pattern.height = row_span + 1;
494 pattern.width = col_span + 1;
495 pattern.alive.clear();
496 pattern.alive.reserve(absolute.size());
497 for (const auto &c : absolute)
498 pattern.alive.append(Coord_Vec<2>{c[0] - min_row, c[1] - min_col});
499}
500
501template <typename T>
502inline T parse_scalar(const std::string &token, const char *format)
503{
504 std::istringstream in(trim_copy(token));
505 T value{};
506 in >> value;
507 ah_domain_error_unless(in) << format << ": cannot parse scalar '" << token << "'";
508 std::string rest;
509 in >> rest;
510 ah_domain_error_unless(rest.empty())
511 << format << ": trailing characters in scalar '" << token << "'";
512 return value;
513}
514
515template <typename T>
516inline T parse_json_number(const std::string &s, std::size_t &pos)
517{
518 while (pos < s.size() and std::isspace(static_cast<unsigned char>(s[pos])))
519 ++pos;
520 const std::size_t start = pos;
521 if (pos < s.size() and (s[pos] == '-' or s[pos] == '+'))
522 ++pos;
523 while (pos < s.size() and std::isdigit(static_cast<unsigned char>(s[pos])))
524 ++pos;
525 if (pos < s.size() and s[pos] == '.')
526 {
527 ++pos;
528 while (pos < s.size() and std::isdigit(static_cast<unsigned char>(s[pos])))
529 ++pos;
530 }
531 if (pos < s.size() and (s[pos] == 'e' or s[pos] == 'E'))
532 {
533 ++pos;
534 if (pos < s.size() and (s[pos] == '-' or s[pos] == '+'))
535 ++pos;
536 while (pos < s.size() and std::isdigit(static_cast<unsigned char>(s[pos])))
537 ++pos;
538 }
539 ah_domain_error_if(start == pos) << "JSON snapshot: expected number";
540 return parse_scalar<T>(s.substr(start, pos - start), "JSON snapshot");
541}
542
543inline ca_size_t parse_json_size_field(const std::string &s, const std::string &key)
544{
545 const std::string needle = "\"" + key + "\"";
546 const std::size_t key_pos = s.find(needle);
547 ah_domain_error_if(key_pos == std::string::npos) << "JSON snapshot: missing field '" << key << "'";
548 std::size_t colon = s.find(':', key_pos + needle.size());
549 ah_domain_error_if(colon == std::string::npos)
550 << "JSON snapshot: missing ':' after '" << key << "'";
551 ++colon;
552 while (colon < s.size() and std::isspace(static_cast<unsigned char>(s[colon])))
553 ++colon;
554 const std::size_t start = colon;
555 while (colon < s.size() and std::isdigit(static_cast<unsigned char>(s[colon])))
556 ++colon;
557 ah_domain_error_if(start == colon)
558 << "JSON snapshot: field '" << key << "' is not an unsigned integer";
559 return parse_size_token(s.substr(start, colon - start), key.c_str());
560}
561
562inline void ensure_stream_ok(const std::ostream &out, const char *fn)
563{
564 ah_runtime_error_if(not out) << fn << ": output stream failed";
565}
566
567template <typename T>
568inline void write_text_scalar(std::ostream &out, const T &value)
569{
570 if constexpr (std::is_integral_v<T> and sizeof(T) == 1 and not std::is_same_v<T, bool>)
571 out << static_cast<int>(value);
572 else
573 out << value;
574}
575
576} // namespace ca_io_detail
577
597template <typename Lattice>
598inline void write_rle(std::ostream &out,
599 const Lattice &frame,
600 const RLE_Write_Options &opts = {},
601 const typename Lattice::state_type &dead = typename Lattice::state_type{})
602{
603 ca_io_detail::require_rank2<Lattice>("write_rle");
604 using coord_t = typename Lattice::coord_type;
605
606 for (const auto &line : ca_io_detail::split_comment_lines(opts.name))
607 out << "#N " << line << '\n';
608 for (const auto &line : ca_io_detail::split_comment_lines(opts.comment))
609 out << "#C " << line << '\n';
610
611 const ca_size_t rows = frame.size(0);
612 const ca_size_t cols = frame.size(1);
613 ca_size_t r0 = 0, c0 = 0, r1 = rows, c1 = cols;
614
615 if (opts.trim_dead_border)
616 {
617 bool any = false;
618 ca_size_t min_r = rows, min_c = cols, max_r = 0, max_c = 0;
619 for (ca_size_t r = 0; r < rows; ++r)
620 for (ca_size_t c = 0; c < cols; ++c)
621 if (frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}) != dead)
622 {
623 any = true;
624 min_r = std::min(min_r, r);
625 min_c = std::min(min_c, c);
626 max_r = std::max(max_r, r);
627 max_c = std::max(max_c, c);
628 }
629 if (any)
630 {
631 r0 = min_r;
632 c0 = min_c;
633 r1 = max_r + 1;
634 c1 = max_c + 1;
635 }
636 else
637 {
638 r0 = c0 = r1 = c1 = 0;
639 }
640 }
641
642 const ca_size_t height = r1 - r0;
643 const ca_size_t width = c1 - c0;
644 out << "x = " << width << ", y = " << height << ", rule = " << opts.rule << '\n';
645
646 std::string body;
647 if (height == 0 or width == 0)
648 {
649 body = "!";
650 }
651 else
652 {
653 for (ca_size_t r = r0; r < r1; ++r)
654 {
655 bool run_alive =
656 frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c0)}) != dead;
657 ca_size_t run = 0;
658 for (ca_size_t c = c0; c < c1; ++c)
659 {
660 const bool alive =
661 frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}) != dead;
662 if (alive == run_alive)
663 ++run;
664 else
665 {
666 ca_io_detail::append_rle_token(body, run, run_alive ? 'o' : 'b');
667 run_alive = alive;
668 run = 1;
669 }
670 }
671 ca_io_detail::append_rle_token(body, run, run_alive ? 'o' : 'b');
672 if (r + 1 < r1)
673 ca_io_detail::append_rle_token(body, 1, '$');
674 }
675 body.push_back('!');
676 }
677
678 ca_io_detail::write_wrapped_rle_body(out, body, opts.line_width);
679 ca_io_detail::ensure_stream_ok(out, "write_rle");
680}
681
690template <typename Lattice>
691[[nodiscard]] inline std::string write_rle_string(
692 const Lattice &frame,
693 const RLE_Write_Options &opts = {},
694 const typename Lattice::state_type &dead = typename Lattice::state_type{})
695{
696 std::ostringstream out;
697 write_rle(out, frame, opts, dead);
698 return out.str();
699}
700
710
731[[nodiscard]] inline RLE_Pattern read_rle(std::istream &in,
732 const ca_size_t max_live_cells = Rle_Default_Max_Live_Cells)
733{
734 RLE_Pattern pattern;
735 std::string line;
736 bool header_seen = false;
737 ca_size_t cur_row = 0;
738 ca_size_t cur_col = 0;
739 ca_size_t run = 0;
740 bool ended = false;
741
742 while (not ended and std::getline(in, line))
743 {
744 if (line.empty())
745 continue;
746 if (line[0] == '#')
747 {
748 if (line.size() >= 2 and (line[1] == 'N' or line[1] == 'n'))
749 pattern.name = ca_io_detail::trim_copy(line.substr(2));
750 else if (line.size() >= 2 and (line[1] == 'C' or line[1] == 'c'))
751 pattern.comments.append(ca_io_detail::trim_copy(line.substr(2)));
752 continue;
753 }
754
755 if (not header_seen)
756 {
757 const std::string x = ca_io_detail::header_value(line, "x");
758 const std::string y = ca_io_detail::header_value(line, "y");
759 ah_domain_error_if(x.empty() or y.empty())
760 << "read_rle: missing x/y header in line '" << line << "'";
761 pattern.width = ca_io_detail::parse_size_token(x, "read_rle x");
762 pattern.height = ca_io_detail::parse_size_token(y, "read_rle y");
763 ah_overflow_error_if(pattern.width > ca_io_detail::Max_Pattern_Extent or
764 pattern.height > ca_io_detail::Max_Pattern_Extent)
765 << "read_rle: pattern size needs coordinates beyond ca_index_t";
766 pattern.rule = ca_io_detail::header_value(line, "rule");
767 header_seen = true;
768 continue;
769 }
770
771 for (const char ch : line)
772 {
773 if (std::isdigit(static_cast<unsigned char>(ch)))
774 {
775 const ca_size_t digit = static_cast<ca_size_t>(ch - '0');
776 ah_overflow_error_if(run > (std::numeric_limits<ca_size_t>::max() - digit) / 10)
777 << "read_rle: run length overflows ca_size_t";
778 run = run * 10 + digit;
779 }
780 else if (ch == 'b' or ch == '.')
781 {
782 const ca_size_t n = run == 0 ? 1 : run;
783 // cur_col <= width, so the subtraction cannot wrap; a sum could
784 ah_domain_error_if(n > pattern.width - cur_col)
785 << "read_rle: dead run exceeds row width";
786 cur_col += n;
787 run = 0;
788 }
789 else if (ch == 'o' or ch == 'A')
790 {
791 const ca_size_t n = run == 0 ? 1 : run;
792 ah_domain_error_if(cur_row >= pattern.height or n > pattern.width - cur_col)
793 << "read_rle: live run exceeds declared dimensions";
794 ah_length_error_if(n > max_live_cells - pattern.alive.size())
795 << "read_rle: more than " << max_live_cells << " live cells";
796 for (ca_size_t k = 0; k < n; ++k)
797 pattern.alive.append(Coord_Vec<2>{static_cast<ca_index_t>(cur_row),
798 static_cast<ca_index_t>(cur_col + k)});
799 cur_col += n;
800 run = 0;
801 }
802 else if (ch == '$')
803 {
804 const ca_size_t n = run == 0 ? 1 : run;
805 ah_domain_error_if(n > pattern.height - cur_row)
806 << "read_rle: row advance exceeds declared height";
807 cur_row += n;
808 cur_col = 0;
809 run = 0;
810 }
811 else if (ch == '!')
812 {
813 ended = true;
814 run = 0;
815 break;
816 }
817 else
818 {
819 ah_domain_error_unless(std::isspace(static_cast<unsigned char>(ch)))
820 << "read_rle: invalid body character '" << ch << "'";
821 }
822 }
823 }
824
825 ah_domain_error_if(not header_seen) << "read_rle: missing header";
826 ah_domain_error_if(run != 0) << "read_rle: dangling run length";
827 return pattern;
828}
829
839[[nodiscard]] inline RLE_Pattern read_rle_string(
840 const std::string &s, const ca_size_t max_live_cells = Rle_Default_Max_Live_Cells)
841{
842 std::istringstream in(s);
843 return read_rle(in, max_live_cells);
844}
845
863template <typename Lattice>
865 const Binary_Cell_Pattern &pattern,
866 Lattice &frame,
867 const typename Lattice::state_type &alive = static_cast<typename Lattice::state_type>(1),
868 const typename Lattice::state_type &dead = typename Lattice::state_type{},
869 const ca_index_t origin_row = 0,
870 const ca_index_t origin_col = 0)
871{
872 ca_io_detail::require_rank2<Lattice>("load_binary_pattern");
873 using coord_t = typename Lattice::coord_type;
874 ah_domain_error_if(origin_row < 0 or origin_col < 0)
875 << "load_binary_pattern: negative destination origin";
876 ah_domain_error_if(pattern.height > frame.size(0) or
877 static_cast<ca_size_t>(origin_row) > frame.size(0) - pattern.height or
878 pattern.width > frame.size(1) or
879 static_cast<ca_size_t>(origin_col) > frame.size(1) - pattern.width)
880 << "load_binary_pattern: pattern " << pattern.height << "x" << pattern.width
881 << " does not fit in frame " << frame.size(0) << "x" << frame.size(1);
882
883 frame.fill(dead);
884 for (const auto &cell : pattern.alive)
885 frame.set(coord_t{origin_row + cell[0], origin_col + cell[1]}, alive);
886}
887
899template <typename Lattice>
901 const Binary_Cell_Pattern &pattern,
902 const typename Lattice::state_type &alive = static_cast<typename Lattice::state_type>(1),
903 const typename Lattice::state_type &dead = typename Lattice::state_type{})
904{
905 ca_io_detail::require_rank2<Lattice>("make_lattice_from_pattern");
906 Lattice frame({pattern.height, pattern.width}, dead);
907 load_binary_pattern(pattern, frame, alive, dead);
908 return frame;
909}
910
923template <typename Lattice>
924inline void write_plaintext(std::ostream &out,
925 const Lattice &frame,
926 const Plaintext_Write_Options &opts = {},
927 const typename Lattice::state_type &dead = typename Lattice::state_type{})
928{
929 ca_io_detail::require_rank2<Lattice>("write_plaintext");
930 using coord_t = typename Lattice::coord_type;
931 for (const auto &line : ca_io_detail::split_comment_lines(opts.comment))
932 out << '!' << line << '\n';
933
934 for (ca_size_t r = 0; r < frame.size(0); ++r)
935 {
936 for (ca_size_t c = 0; c < frame.size(1); ++c)
937 out << (frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}) == dead
938 ? opts.dead
939 : opts.alive);
940 out << '\n';
941 }
942 ca_io_detail::ensure_stream_ok(out, "write_plaintext");
943}
944
953template <typename Lattice>
954[[nodiscard]] inline std::string write_plaintext_string(
955 const Lattice &frame,
956 const Plaintext_Write_Options &opts = {},
957 const typename Lattice::state_type &dead = typename Lattice::state_type{})
958{
959 std::ostringstream out;
960 write_plaintext(out, frame, opts, dead);
961 return out.str();
962}
963
976[[nodiscard]] inline Binary_Cell_Pattern read_plaintext(std::istream &in)
977{
978 Binary_Cell_Pattern pattern;
980 std::string line;
981 while (std::getline(in, line))
982 {
983 if (line.empty())
984 {
985 rows.append(std::string{});
986 continue;
987 }
988 if (line[0] == '!')
989 {
990 pattern.comments.append(ca_io_detail::trim_copy(line.substr(1)));
991 continue;
992 }
993 std::string row;
994 for (const char c : line)
995 if (c == 'O' or c == 'o' or c == '*' or c == '.')
996 row.push_back(c);
997 else
998 {
999 ah_domain_error_unless(std::isspace(static_cast<unsigned char>(c)))
1000 << "read_plaintext: invalid character '" << c << "'";
1001 }
1002 rows.append(std::move(row));
1003 }
1004
1005 pattern.height = rows.size();
1006 pattern.width = 0;
1007 for (const auto &row : rows)
1008 pattern.width = std::max(pattern.width, row.size());
1009 for (ca_size_t r = 0; r < rows.size(); ++r)
1010 for (ca_size_t c = 0; c < rows(r).size(); ++c)
1011 if (rows(r)[c] == 'O' or rows(r)[c] == 'o' or rows(r)[c] == '*')
1012 pattern.alive.append(Coord_Vec<2>{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)});
1013 return pattern;
1014}
1015
1020[[nodiscard]] inline Binary_Cell_Pattern read_plaintext_string(const std::string &s)
1021{
1022 std::istringstream in(s);
1023 return read_plaintext(in);
1024}
1025
1039template <typename Lattice>
1040inline void write_life_106(std::ostream &out,
1041 const Lattice &frame,
1042 const typename Lattice::state_type &dead = typename Lattice::state_type{})
1043{
1044 ca_io_detail::require_rank2<Lattice>("write_life_106");
1045 using coord_t = typename Lattice::coord_type;
1046 out << "#Life 1.06\n";
1047 for (ca_size_t r = 0; r < frame.size(0); ++r)
1048 for (ca_size_t c = 0; c < frame.size(1); ++c)
1049 if (frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}) != dead)
1050 out << c << ' ' << r << '\n';
1051 ca_io_detail::ensure_stream_ok(out, "write_life_106");
1052}
1053
1068[[nodiscard]] inline Binary_Cell_Pattern read_life_106(std::istream &in)
1069{
1070 Binary_Cell_Pattern pattern;
1071 std::string line;
1072 bool header_seen = false;
1073 Array<Coord_Vec<2>> absolute;
1074 ca_index_t min_r = 0, min_c = 0, max_r = 0, max_c = 0;
1075 bool have = false;
1076
1077 while (std::getline(in, line))
1078 {
1079 const std::string t = ca_io_detail::trim_copy(line);
1080 if (t.empty())
1081 continue;
1082 if (t[0] == '#')
1083 {
1084 if (t == "#Life 1.06")
1085 header_seen = true;
1086 else if (t.size() >= 2 and (t[1] == 'D' or t[1] == 'd'))
1087 pattern.comments.append(ca_io_detail::trim_copy(t.substr(2)));
1088 continue;
1089 }
1090 std::istringstream ls(t);
1091 std::string xs, ys, extra;
1092 ls >> xs >> ys >> extra;
1093 ah_domain_error_if(not extra.empty()) << "read_life_106: too many fields in '" << line << "'";
1094 const ca_index_t col = ca_io_detail::parse_index_token(xs, "read_life_106 x");
1095 const ca_index_t row = ca_io_detail::parse_index_token(ys, "read_life_106 y");
1096 absolute.append(Coord_Vec<2>{row, col});
1097 if (not have)
1098 {
1099 min_r = max_r = row;
1100 min_c = max_c = col;
1101 have = true;
1102 }
1103 else
1104 {
1105 min_r = std::min(min_r, row);
1106 min_c = std::min(min_c, col);
1107 max_r = std::max(max_r, row);
1108 max_c = std::max(max_c, col);
1109 }
1110 }
1111
1112 ah_domain_error_unless(header_seen) << "read_life_106: missing #Life 1.06 header";
1113 ca_io_detail::finalise_absolute_pattern(pattern, absolute, have, min_r, min_c, max_r, max_c,
1114 "read_life_106");
1115 return pattern;
1116}
1117
1133template <typename Lattice>
1134inline void write_life_105(std::ostream &out,
1135 const Lattice &frame,
1136 const std::string &comment = {},
1137 const typename Lattice::state_type &dead = typename Lattice::state_type{})
1138{
1139 ca_io_detail::require_rank2<Lattice>("write_life_105");
1140 using coord_t = typename Lattice::coord_type;
1141 out << "#Life 1.05\n";
1142 for (const auto &line : ca_io_detail::split_comment_lines(comment))
1143 out << "#D " << line << '\n';
1144 out << "#P 0 0\n";
1145 for (ca_size_t r = 0; r < frame.size(0); ++r)
1146 {
1147 for (ca_size_t c = 0; c < frame.size(1); ++c)
1148 out << (frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}) == dead
1149 ? '.'
1150 : '*');
1151 out << '\n';
1152 }
1153 ca_io_detail::ensure_stream_ok(out, "write_life_105");
1154}
1155
1170[[nodiscard]] inline Binary_Cell_Pattern read_life_105(std::istream &in)
1171{
1172 Binary_Cell_Pattern pattern;
1173 Array<Coord_Vec<2>> absolute;
1174 std::string line;
1175 bool header_seen = false;
1176 bool in_block = false;
1177 ca_index_t block_col = 0, block_row = 0, local_row = 0;
1178 ca_index_t min_r = 0, min_c = 0, max_r = 0, max_c = 0;
1179 bool have_extent = false;
1180
1181 auto touch_extent = [&](ca_index_t row, ca_index_t col)
1182 {
1183 if (not have_extent)
1184 {
1185 min_r = max_r = row;
1186 min_c = max_c = col;
1187 have_extent = true;
1188 }
1189 else
1190 {
1191 min_r = std::min(min_r, row);
1192 min_c = std::min(min_c, col);
1193 max_r = std::max(max_r, row);
1194 max_c = std::max(max_c, col);
1195 }
1196 };
1197
1198 while (std::getline(in, line))
1199 {
1200 const std::string t = ca_io_detail::trim_copy(line);
1201 if (t.empty())
1202 continue;
1203 if (t[0] == '#')
1204 {
1205 if (t == "#Life 1.05")
1206 {
1207 header_seen = true;
1208 continue;
1209 }
1210 if (t.size() >= 2 and (t[1] == 'D' or t[1] == 'd'))
1211 {
1212 pattern.comments.append(ca_io_detail::trim_copy(t.substr(2)));
1213 continue;
1214 }
1215 if (t.size() >= 2 and (t[1] == 'P' or t[1] == 'p'))
1216 {
1217 std::istringstream ps(t.substr(2));
1218 std::string xs, ys, extra;
1219 ps >> xs >> ys >> extra;
1220 ah_domain_error_if(xs.empty() or ys.empty() or not extra.empty())
1221 << "read_life_105: malformed #P line '" << line << "'";
1222 block_col = ca_io_detail::parse_index_token(xs, "read_life_105 #P x");
1223 block_row = ca_io_detail::parse_index_token(ys, "read_life_105 #P y");
1224 local_row = 0;
1225 in_block = true;
1226 continue;
1227 }
1228 continue;
1229 }
1230
1231 ah_domain_error_unless(in_block) << "read_life_105: pattern row before #P block";
1232 ca_index_t local_col = 0;
1233 for (const char c : line)
1234 {
1235 if (c == '*' or c == 'O' or c == 'o' or c == '.')
1236 {
1237 const ca_index_t row = ca_io_detail::checked_coord_add(block_row, local_row,
1238 "read_life_105");
1239 const ca_index_t col = ca_io_detail::checked_coord_add(block_col, local_col,
1240 "read_life_105");
1241 touch_extent(row, col);
1242 if (c == '*' or c == 'O' or c == 'o')
1243 absolute.append(Coord_Vec<2>{row, col});
1244 ++local_col;
1245 }
1246 else
1247 {
1248 ah_domain_error_unless(std::isspace(static_cast<unsigned char>(c)))
1249 << "read_life_105: invalid row character '" << c << "'";
1250 }
1251 }
1252 ++local_row;
1253 }
1254
1255 ah_domain_error_unless(header_seen) << "read_life_105: missing #Life 1.05 header";
1256 ca_io_detail::finalise_absolute_pattern(pattern, absolute, have_extent, min_r, min_c, max_r, max_c,
1257 "read_life_105");
1258 return pattern;
1259}
1260
1275template <typename Lattice>
1276inline void write_csv(std::ostream &out, const Lattice &frame, const CSV_Options &opts = {})
1277{
1278 ca_io_detail::require_rank2<Lattice>("write_csv");
1279 using coord_t = typename Lattice::coord_type;
1280 for (ca_size_t r = 0; r < frame.size(0); ++r)
1281 {
1282 for (ca_size_t c = 0; c < frame.size(1); ++c)
1283 {
1284 if (c != 0)
1285 out << opts.delimiter;
1286 ca_io_detail::write_text_scalar(
1287 out, frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}));
1288 }
1289 out << '\n';
1290 }
1291 ca_io_detail::ensure_stream_ok(out, "write_csv");
1292}
1293
1310template <typename T>
1311[[nodiscard]] inline Grid_Snapshot<T> read_csv_snapshot(std::istream &in,
1312 const CSV_Options &opts = {})
1313{
1314 Grid_Snapshot<T> snap;
1315 std::string line;
1316 ca_size_t row = 0;
1317 while (std::getline(in, line))
1318 {
1319 if (opts.skip_empty_lines and ca_io_detail::blank(line))
1320 continue;
1321 Array<T> values;
1322 std::string token;
1323 std::istringstream ls(line);
1324 while (std::getline(ls, token, opts.delimiter))
1325 values.append(ca_io_detail::parse_scalar<T>(token, "CSV snapshot"));
1326 if (line.empty() and not opts.skip_empty_lines)
1327 values.append(T{});
1328 if (row == 0)
1329 snap.width = values.size();
1330 ah_domain_error_if(values.size() != snap.width)
1331 << "read_csv_snapshot: row " << row << " has width " << values.size() << " instead of "
1332 << snap.width;
1333 for (const T &v : values)
1334 snap.cells.append(v);
1335 ++row;
1336 }
1337 snap.height = row;
1338 return snap;
1339}
1340
1351template <typename Lattice, typename T>
1352[[nodiscard]] inline Lattice make_lattice_from_snapshot(const Grid_Snapshot<T> &snap)
1353{
1354 ca_io_detail::require_rank2<Lattice>("make_lattice_from_snapshot");
1355 using state_t = typename Lattice::state_type;
1356 using coord_t = typename Lattice::coord_type;
1357 Lattice frame({snap.height, snap.width}, state_t{});
1358 for (ca_size_t r = 0; r < snap.height; ++r)
1359 for (ca_size_t c = 0; c < snap.width; ++c)
1360 frame.set(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)},
1361 static_cast<state_t>(snap.at(r, c)));
1362 return frame;
1363}
1364
1382template <typename Lattice>
1383inline void write_json(std::ostream &out, const Lattice &frame, const JSON_Write_Options &opts = {})
1384{
1385 ca_io_detail::require_rank2<Lattice>("write_json");
1386 using coord_t = typename Lattice::coord_type;
1387
1388 const auto nl = opts.pretty ? "\n" : "";
1389 const auto i1 = opts.pretty ? " " : "";
1390 const auto i2 = opts.pretty ? " " : "";
1391 const auto sp = opts.pretty ? " " : "";
1392
1393 out << '{' << nl;
1394 out << i1 << "\"type\":" << sp << "\"Aleph::CA::frame\"," << nl;
1395 out << i1 << "\"rank\":" << sp << "2," << nl;
1396 out << i1 << "\"height\":" << sp << frame.size(0) << ',' << nl;
1397 out << i1 << "\"width\":" << sp << frame.size(1);
1398 if (not opts.rule.empty())
1399 out << ',' << nl << i1 << "\"rule\":" << sp << '"' << ca_io_detail::json_escape(opts.rule) << '"';
1400 out << ',' << nl << i1 << "\"cells\":" << sp << '[' << nl;
1401 for (ca_size_t r = 0; r < frame.size(0); ++r)
1402 {
1403 out << i2 << '[';
1404 for (ca_size_t c = 0; c < frame.size(1); ++c)
1405 {
1406 if (c != 0)
1407 out << ',';
1408 if (opts.pretty)
1409 out << ' ';
1410 ca_io_detail::write_text_scalar(
1411 out, frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}));
1412 }
1413 if (opts.pretty and frame.size(1) != 0)
1414 out << ' ';
1415 out << ']';
1416 if (r + 1 < frame.size(0))
1417 out << ',';
1418 out << nl;
1419 }
1420 out << i1 << ']' << nl << "}" << nl;
1421 ca_io_detail::ensure_stream_ok(out, "write_json");
1422}
1423
1438template <typename T>
1439[[nodiscard]] inline Grid_Snapshot<T> read_json_snapshot(std::istream &in)
1440{
1441 std::ostringstream ss;
1442 ss << in.rdbuf();
1443 const std::string s = ss.str();
1444 Grid_Snapshot<T> snap;
1445 snap.height = ca_io_detail::parse_json_size_field(s, "height");
1446 snap.width = ca_io_detail::parse_json_size_field(s, "width");
1447
1448 const std::size_t key = s.find("\"cells\"");
1449 ah_domain_error_if(key == std::string::npos) << "JSON snapshot: missing cells field";
1450 std::size_t pos = s.find('[', key);
1451 ah_domain_error_if(pos == std::string::npos) << "JSON snapshot: missing cells array";
1452 ++pos;
1453
1454 ca_size_t rows = 0;
1455 while (true)
1456 {
1457 while (pos < s.size() and (std::isspace(static_cast<unsigned char>(s[pos])) or s[pos] == ','))
1458 ++pos;
1459 ah_domain_error_if(pos >= s.size()) << "JSON snapshot: unterminated cells array";
1460 if (s[pos] == ']')
1461 {
1462 ++pos;
1463 break;
1464 }
1465 ah_domain_error_if(s[pos] != '[') << "JSON snapshot: expected row array";
1466 ++pos;
1467 ca_size_t cols = 0;
1468 while (true)
1469 {
1470 while (pos < s.size() and std::isspace(static_cast<unsigned char>(s[pos])))
1471 ++pos;
1472 ah_domain_error_if(pos >= s.size()) << "JSON snapshot: unterminated row";
1473 if (s[pos] == ']')
1474 {
1475 ++pos;
1476 break;
1477 }
1478 if (cols != 0)
1479 {
1480 ah_domain_error_if(s[pos] != ',') << "JSON snapshot: expected comma";
1481 ++pos;
1482 }
1483 snap.cells.append(ca_io_detail::parse_json_number<T>(s, pos));
1484 ++cols;
1485 }
1487 << "JSON snapshot: row " << rows << " has width " << cols << " instead of " << snap.width;
1488 ++rows;
1489 }
1490
1492 << "JSON snapshot: got " << rows << " rows instead of " << snap.height;
1493 return snap;
1494}
1495
1512template <typename Lattice, typename Mapper>
1513inline void write_pgm(std::ostream &out,
1514 const Lattice &frame,
1515 Mapper &&mapper,
1516 const NetPBM_Write_Options &opts = {})
1517 requires requires(Mapper &&m, const typename Lattice::state_type &v) {
1518 { m(v) } -> std::convertible_to<std::uint8_t>;
1519 }
1520{
1521 ca_io_detail::require_rank2<Lattice>("write_pgm");
1522 using coord_t = typename Lattice::coord_type;
1523 ah_domain_error_if(opts.max_value == 0 or opts.max_value > 255)
1524 << "write_pgm: only 8-bit max_value in [1,255] is supported";
1525 out << "P5\n" << frame.size(1) << ' ' << frame.size(0) << '\n' << opts.max_value << '\n';
1526 for (ca_size_t r = 0; r < frame.size(0); ++r)
1527 for (ca_size_t c = 0; c < frame.size(1); ++c)
1528 {
1529 const std::uint8_t v = static_cast<std::uint8_t>(
1530 mapper(frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)})));
1531 out.write(reinterpret_cast<const char *>(&v), 1);
1532 }
1533 ca_io_detail::ensure_stream_ok(out, "write_pgm");
1534}
1535
1543template <typename Lattice>
1544inline void write_pgm(std::ostream &out, const Lattice &frame, const NetPBM_Write_Options &opts = {})
1545{
1546 write_pgm(out, frame, Binary_Gray_Mapper<typename Lattice::state_type>{}, opts);
1547}
1548
1564template <typename Lattice, typename Mapper>
1565inline void write_ppm(std::ostream &out,
1566 const Lattice &frame,
1567 Mapper &&mapper,
1568 const NetPBM_Write_Options &opts = {})
1569 requires requires(Mapper &&m, const typename Lattice::state_type &v) {
1570 { m(v) } -> std::convertible_to<RGB8>;
1571 }
1572{
1573 ca_io_detail::require_rank2<Lattice>("write_ppm");
1574 using coord_t = typename Lattice::coord_type;
1575 ah_domain_error_if(opts.max_value == 0 or opts.max_value > 255)
1576 << "write_ppm: only 8-bit max_value in [1,255] is supported";
1577 out << "P6\n" << frame.size(1) << ' ' << frame.size(0) << '\n' << opts.max_value << '\n';
1578 for (ca_size_t r = 0; r < frame.size(0); ++r)
1579 for (ca_size_t c = 0; c < frame.size(1); ++c)
1580 {
1581 const RGB8 rgb =
1582 mapper(frame.at(coord_t{static_cast<ca_index_t>(r), static_cast<ca_index_t>(c)}));
1583 const char bytes[3] = {static_cast<char>(rgb.r), static_cast<char>(rgb.g),
1584 static_cast<char>(rgb.b)};
1585 out.write(bytes, 3);
1586 }
1587 ca_io_detail::ensure_stream_ok(out, "write_ppm");
1588}
1589
1597template <typename Lattice>
1598inline void write_ppm(std::ostream &out, const Lattice &frame, const NetPBM_Write_Options &opts = {})
1599{
1600 write_ppm(out, frame, Binary_RGB_Mapper<typename Lattice::state_type>{}, opts);
1601}
1602
1615{
1616 std::ostream *out_ = nullptr;
1617 bool first_ = true;
1618 bool closed_ = false;
1620
1621public:
1630 explicit JSON_Frame_Stream_Writer(std::ostream &out, JSON_Write_Options opts = {})
1631 : out_(&out), opts_(std::move(opts))
1632 {
1633 *out_ << "{\n \"type\": \"Aleph::CA::frame-stream\",\n \"frames\": [\n";
1634 ca_io_detail::ensure_stream_ok(*out_, "JSON_Frame_Stream_Writer");
1635 }
1636
1639
1646 {
1647 if (out_ != nullptr and not closed_)
1648 {
1649 try
1650 {
1651 close();
1652 }
1653 catch (...)
1654 {}
1655 }
1656 }
1657
1668 template <typename Lattice>
1669 void accept(std::size_t step, const Lattice &frame)
1670 {
1671 ca_io_detail::require_rank2<Lattice>("JSON_Frame_Stream_Writer::accept");
1672 ah_runtime_error_if(closed_) << "JSON_Frame_Stream_Writer::accept: stream already closed";
1673 if (not first_)
1674 *out_ << ",\n";
1675 first_ = false;
1676 *out_ << " {\n \"step\": " << step << ",\n \"frame\": ";
1677 JSON_Write_Options compact = opts_;
1678 compact.pretty = false;
1679 write_json(*out_, frame, compact);
1680 *out_ << " }";
1681 ca_io_detail::ensure_stream_ok(*out_, "JSON_Frame_Stream_Writer::accept");
1682 }
1683
1691 void close()
1692 {
1693 if (closed_)
1694 return;
1695 *out_ << "\n ]\n}\n";
1696 closed_ = true;
1697 ca_io_detail::ensure_stream_ok(*out_, "JSON_Frame_Stream_Writer::close");
1698 }
1699};
1700
1701// Non-throwing parser overloads.
1702//
1703// Each `try_read_*` wraps the corresponding throwing reader above and returns
1704// `Aleph::expected<Result, std::string>`: the parsed value on success, or the
1705// error message on failure. Useful when parsing untrusted input where an
1706// invalid file is an expected outcome rather than an exceptional one. The
1707// throwing readers are unchanged.
1708// ---------------------------------------------------------------------------
1709
1710namespace ca_io_detail {
1711
1715template <class F>
1716[[nodiscard]] auto try_parse(F &&parse, const char *context)
1717 -> expected<std::invoke_result_t<F &>, std::string>
1718{
1719 try
1720 {
1721 return parse();
1722 }
1723 catch (const std::exception &e)
1724 {
1725 return unexpected<std::string>(std::string(context) + ": " + e.what());
1726 }
1727 catch (...)
1728 {
1729 return unexpected<std::string>(std::string(context) + ": unknown error");
1730 }
1731}
1732
1733} // namespace ca_io_detail
1734
1751 std::istream &in, const ca_size_t max_live_cells = Rle_Default_Max_Live_Cells)
1752{
1753 return ca_io_detail::try_parse([&]
1754 {
1755 return read_rle(in, max_live_cells);
1756 }, "try_read_rle");
1757}
1758
1775 const std::string &s, const ca_size_t max_live_cells = Rle_Default_Max_Live_Cells)
1776{
1777 return ca_io_detail::try_parse([&]
1778 {
1779 return read_rle_string(s, max_live_cells);
1780 }, "try_read_rle_string");
1781}
1782
1798{
1799 return ca_io_detail::try_parse([&]
1800 {
1801 return read_plaintext(in);
1802 }, "try_read_plaintext");
1803}
1804
1820{
1821 return ca_io_detail::try_parse([&]
1822 {
1823 return read_life_105(in);
1824 }, "try_read_life_105");
1825}
1826
1842{
1843 return ca_io_detail::try_parse([&]
1844 {
1845 return read_life_106(in);
1846 }, "try_read_life_106");
1847}
1848
1865template <class T>
1866[[nodiscard]] inline expected<Grid_Snapshot<T>, std::string> try_read_csv_snapshot(
1867 std::istream &in,
1868 const CSV_Options &opts = {})
1869{
1870 return ca_io_detail::try_parse([&]
1871 {
1872 return read_csv_snapshot<T>(in, opts);
1873 }, "try_read_csv_snapshot");
1874}
1875
1876} // namespace CA
1877} // namespace Aleph
1878
1879#endif // CA_IO_H
C++20/23 compatibility layer: feature detection + Aleph:: polyfills.
Exception handling system with formatted messages for Aleph-w.
#define ah_length_error_if(C)
Throws std::length_error if condition holds.
Definition ah-errors.H:846
#define ah_domain_error_unless(C)
Throws std::domain_error if condition does NOT hold.
Definition ah-errors.H:686
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
static int cell(const aleph_ca_engine_t *e, size_t r, size_t c)
Definition c_abi_smoke.c:53
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
Common typedefs and tag types for the Cellular Automata module.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void clear() noexcept
Empties the container.
Definition tpl_array.H:435
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Streaming JSON writer for CA trajectories.
Definition ca-io.H:1615
JSON_Frame_Stream_Writer(const JSON_Frame_Stream_Writer &)=delete
void close()
Finish the stream.
Definition ca-io.H:1691
JSON_Frame_Stream_Writer(std::ostream &out, JSON_Write_Options opts={})
Start a JSON frame stream.
Definition ca-io.H:1630
~JSON_Frame_Stream_Writer()
Finish the JSON document if it is still open.
Definition ca-io.H:1645
void accept(std::size_t step, const Lattice &frame)
Append one frame to the stream.
Definition ca-io.H:1669
Lattice that adds boundary-aware access on top of a storage.
void set(const coord_type &c, const state_type &v)
Strict write: throws if c is out of range.
typename Storage::state_type state_type
typename Storage::coord_type coord_type
static constexpr std::size_t rank
ca_size_t size() const noexcept
void fill(const state_type &value)
Set every cell to value.
state_type at(const coord_type &c) const
Strict access: throws if c is out of range.
Minimal std::expected-style result type for C++20.
Wrapper for the error value used to initialize an expected.
Storage + topology that carries the cell values.
static mpfr_t y
Definition mpfr_mul_d.c:3
std::string trim_copy(const std::string &s)
Definition ca-io.H:270
std::string rle_token(ca_size_t n, char glyph)
Definition ca-io.H:402
void finalise_absolute_pattern(Binary_Cell_Pattern &pattern, const Array< Coord_Vec< 2 > > &absolute, const bool have_extent, const ca_index_t min_row, const ca_index_t min_col, const ca_index_t max_row, const ca_index_t max_col, const char *what)
Definition ca-io.H:466
auto try_parse(F &&parse, const char *context) -> expected< std::invoke_result_t< F & >, std::string >
Invoke a parser, translating any thrown exception into the error channel of expected.
Definition ca-io.H:1716
ca_index_t checked_coord_add(const ca_index_t a, const ca_index_t b, const char *what)
a + b for coordinates, or std::overflow_error if it does not fit.
Definition ca-io.H:347
void ensure_stream_ok(const std::ostream &out, const char *fn)
Definition ca-io.H:562
bool blank(const std::string &s)
Definition ca-io.H:288
T parse_scalar(const std::string &token, const char *format)
Definition ca-io.H:502
ca_index_t parse_index_token(const std::string &s, const char *what)
Definition ca-io.H:313
Array< std::string > split_comment_lines(const std::string &comment)
Definition ca-io.H:355
constexpr ca_size_t Max_Pattern_Extent
Largest width or height of a pattern: its cells have coordinates from 0 to Max_Coordinate.
Definition ca-io.H:344
ca_size_t parse_json_size_field(const std::string &s, const std::string &key)
Definition ca-io.H:543
void write_text_scalar(std::ostream &out, const T &value)
Definition ca-io.H:568
std::string header_value(const std::string &line, const std::string &key)
Definition ca-io.H:450
std::string json_escape(const std::string &s)
Definition ca-io.H:367
ca_size_t parse_size_token(const std::string &s, const char *what)
Definition ca-io.H:296
T parse_json_number(const std::string &s, std::size_t &pos)
Definition ca-io.H:516
std::string lower_copy(std::string s)
Definition ca-io.H:281
void require_rank2(const char *fn)
Definition ca-io.H:263
void append_rle_token(std::string &body, ca_size_t n, char glyph)
Definition ca-io.H:413
void write_wrapped_rle_body(std::ostream &out, const std::string &body, const std::size_t line_width)
Definition ca-io.H:418
constexpr ca_index_t Max_Coordinate
Largest coordinate of a cell.
Definition ca-io.H:340
expected< Binary_Cell_Pattern, std::string > try_read_life_106(std::istream &in)
Non-throwing variant of read_life_106.
Definition ca-io.H:1841
Lattice make_lattice_from_snapshot(const Grid_Snapshot< T > &snap)
Construct a lattice from a numeric snapshot.
Definition ca-io.H:1352
void write_pgm(std::ostream &out, const Lattice &frame, Mapper &&mapper, const NetPBM_Write_Options &opts={})
Write a binary PGM (P5) image.
Definition ca-io.H:1513
void write_life_105(std::ostream &out, const Lattice &frame, const std::string &comment={}, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Write a Life 1.05 file.
Definition ca-io.H:1134
void write_plaintext(std::ostream &out, const Lattice &frame, const Plaintext_Write_Options &opts={}, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Write a Life plaintext (.cells) pattern.
Definition ca-io.H:924
Binary_Cell_Pattern read_plaintext_string(const std::string &s)
Read a Life plaintext pattern from a string.
Definition ca-io.H:1020
void write_life_106(std::ostream &out, const Lattice &frame, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Write a Life 1.06 file.
Definition ca-io.H:1040
std::ptrdiff_t ca_index_t
Signed coordinate component used by lattices and neighborhoods.
Definition ca-traits.H:60
expected< RLE_Pattern, std::string > try_read_rle_string(const std::string &s, const ca_size_t max_live_cells=Rle_Default_Max_Live_Cells)
Non-throwing variant of read_rle_string.
Definition ca-io.H:1774
std::array< ca_index_t, N > Coord_Vec
Default coordinate vector.
Definition ca-traits.H:69
constexpr ca_size_t Rle_Default_Max_Live_Cells
Default upper bound on the live cells read_rle() stores.
Definition ca-io.H:709
expected< Binary_Cell_Pattern, std::string > try_read_plaintext(std::istream &in)
Non-throwing variant of read_plaintext.
Definition ca-io.H:1797
std::string write_plaintext_string(const Lattice &frame, const Plaintext_Write_Options &opts={}, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Return a Life plaintext document.
Definition ca-io.H:954
void write_rle(std::ostream &out, const Lattice &frame, const RLE_Write_Options &opts={}, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Write a 2D frame in Conway RLE format.
Definition ca-io.H:598
void write_ppm(std::ostream &out, const Lattice &frame, Mapper &&mapper, const NetPBM_Write_Options &opts={})
Write a binary PPM (P6) image.
Definition ca-io.H:1565
Binary_Cell_Pattern read_life_105(std::istream &in)
Read a Life 1.05 pattern.
Definition ca-io.H:1170
expected< RLE_Pattern, std::string > try_read_rle(std::istream &in, const ca_size_t max_live_cells=Rle_Default_Max_Live_Cells)
Non-throwing variant of read_rle.
Definition ca-io.H:1750
void write_csv(std::ostream &out, const Lattice &frame, const CSV_Options &opts={})
Write a numeric CSV snapshot.
Definition ca-io.H:1276
std::string write_rle_string(const Lattice &frame, const RLE_Write_Options &opts={}, const typename Lattice::state_type &dead=typename Lattice::state_type{})
Return a frame encoded as Conway RLE.
Definition ca-io.H:691
RLE_Pattern read_rle(std::istream &in, const ca_size_t max_live_cells=Rle_Default_Max_Live_Cells)
Read a Conway RLE pattern.
Definition ca-io.H:731
Grid_Snapshot< T > read_json_snapshot(std::istream &in)
Read a JSON numeric snapshot produced by write_json.
Definition ca-io.H:1439
Binary_Cell_Pattern read_life_106(std::istream &in)
Read a Life 1.06 pattern.
Definition ca-io.H:1068
Binary_Cell_Pattern read_plaintext(std::istream &in)
Read a Life plaintext (.cells) pattern.
Definition ca-io.H:976
void write_json(std::ostream &out, const Lattice &frame, const JSON_Write_Options &opts={})
Write a JSON snapshot.
Definition ca-io.H:1383
std::size_t ca_size_t
Unsigned size component used for extents and counts.
Definition ca-traits.H:63
expected< Grid_Snapshot< T >, std::string > try_read_csv_snapshot(std::istream &in, const CSV_Options &opts={})
Non-throwing variant of read_csv_snapshot.
Definition ca-io.H:1866
RLE_Pattern read_rle_string(const std::string &s, const ca_size_t max_live_cells=Rle_Default_Max_Live_Cells)
Read a Conway RLE pattern from a string.
Definition ca-io.H:839
Lattice make_lattice_from_pattern(const Binary_Cell_Pattern &pattern, const typename Lattice::state_type &alive=static_cast< typename Lattice::state_type >(1), const typename Lattice::state_type &dead=typename Lattice::state_type{})
Construct a lattice with the exact dimensions of a pattern.
Definition ca-io.H:900
void load_binary_pattern(const Binary_Cell_Pattern &pattern, Lattice &frame, const typename Lattice::state_type &alive=static_cast< typename Lattice::state_type >(1), const typename Lattice::state_type &dead=typename Lattice::state_type{}, const ca_index_t origin_row=0, const ca_index_t origin_col=0)
Fill a lattice from a binary pattern.
Definition ca-io.H:864
Grid_Snapshot< T > read_csv_snapshot(std::istream &in, const CSV_Options &opts={})
Read a numeric CSV snapshot.
Definition ca-io.H:1311
expected< Binary_Cell_Pattern, std::string > try_read_life_105(std::istream &in)
Non-throwing variant of read_life_105.
Definition ca-io.H:1819
Main namespace for Aleph-w library functions.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Binary pattern shared by RLE, plaintext and Life formats.
Definition ca-io.H:104
std::string name
optional pattern name
Definition ca-io.H:110
ca_index_t origin_row
original row offset before normalisation
Definition ca-io.H:107
ca_size_t height
number of rows
Definition ca-io.H:106
ca_size_t width
number of columns
Definition ca-io.H:105
Array< std::string > comments
format comments without marker prefixes
Definition ca-io.H:111
ca_index_t origin_col
original column offset before normalisation
Definition ca-io.H:108
std::string rule
optional rule string, e.g. B3/S23
Definition ca-io.H:109
Array< Coord_Vec< 2 > > alive
live cells as {row, col}
Definition ca-io.H:112
Default binary grayscale mapper.
Definition ca-io.H:221
std::uint8_t alive_value
grayscale for live cells
Definition ca-io.H:224
std::uint8_t dead_value
grayscale for dead cells
Definition ca-io.H:223
State dead
state considered dead
Definition ca-io.H:222
std::uint8_t operator()(const State &v) const
Map a cell to one byte.
Definition ca-io.H:230
Default binary RGB mapper.
Definition ca-io.H:245
RGB8 dead_colour
colour for dead cells
Definition ca-io.H:247
State dead
state considered dead
Definition ca-io.H:246
RGB8 alive_colour
colour for live cells
Definition ca-io.H:248
RGB8 operator()(const State &v) const
Map a cell to RGB.
Definition ca-io.H:254
Options controlling CSV output and input.
Definition ca-io.H:185
char delimiter
separator between cells
Definition ca-io.H:186
bool skip_empty_lines
reader ignores empty/whitespace-only rows
Definition ca-io.H:187
Dense numeric snapshot used by CSV and JSON readers.
Definition ca-io.H:128
ca_size_t width
number of columns
Definition ca-io.H:129
ca_size_t height
number of rows
Definition ca-io.H:130
Array< T > cells
row-major payload
Definition ca-io.H:131
T at(ca_size_t row, ca_size_t col) const
Return the value at (row, col).
Definition ca-io.H:142
Options controlling JSON snapshot output.
Definition ca-io.H:196
bool pretty
pretty-print with indentation
Definition ca-io.H:197
std::string rule
optional rule field
Definition ca-io.H:198
Options controlling NetPBM output.
Definition ca-io.H:207
std::uint16_t max_value
NetPBM maximum sample value.
Definition ca-io.H:208
Options controlling Life plaintext output.
Definition ca-io.H:173
char dead
glyph for dead cells
Definition ca-io.H:175
char alive
glyph for live cells
Definition ca-io.H:174
std::string comment
optional ! comments, split on newlines
Definition ca-io.H:176
RGB byte triplet used by PPM exporters.
Definition ca-io.H:85
std::uint8_t g
green channel
Definition ca-io.H:87
friend constexpr bool operator==(RGB8, RGB8) noexcept=default
std::uint8_t b
blue channel
Definition ca-io.H:88
std::uint8_t r
red channel
Definition ca-io.H:86
Options controlling Conway RLE output.
Definition ca-io.H:159
std::string rule
rule field emitted in the header
Definition ca-io.H:160
std::size_t line_width
body wrap width; 0 disables wrapping
Definition ca-io.H:164
std::string comment
optional #C lines, split on newlines
Definition ca-io.H:162
bool trim_dead_border
crop to the live-cell bounding box
Definition ca-io.H:163
std::string name
optional #N line
Definition ca-io.H:161
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
C++20 concepts for the Cellular Automata module.