diff options
author | kaiwu <kaiwu2004@gmail.com> | 2022-03-14 18:37:57 +0800 |
---|---|---|
committer | kaiwu <kaiwu2004@gmail.com> | 2022-03-14 18:37:57 +0800 |
commit | 88509ee467b955f9cd23b7d02c16f2f35583cb0d (patch) | |
tree | 2b15d5f0ec2878ae67fce4c36a1151808d657ef5 | |
parent | 5eb187ae03d845e83b78a727533d311643adfd39 (diff) | |
download | advent-of-code-88509ee467b955f9cd23b7d02c16f2f35583cb0d.tar.gz advent-of-code-88509ee467b955f9cd23b7d02c16f2f35583cb0d.zip |
per line
-rw-r--r-- | src/common.cpp | 11 | ||||
-rw-r--r-- | src/common.h | 15 |
2 files changed, 23 insertions, 3 deletions
diff --git a/src/common.cpp b/src/common.cpp index be45494..d608a22 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -19,6 +19,13 @@ line_view load_file(const char* path) { return lv; } -line_view next_line(line_view file) { - return {nullptr, 0}; +line_view next_line(line_view file, size_t* offset) { + const char* p1 = file.line + *offset; + const char* p2 = p1; + const char* end = file.line + file.length; + while (p2 < end && *p2 != '\n') { + p2++; + } + *offset = p2 - file.line + 1; + return {p1, static_cast<size_t>(p2 - p1 + 1)}; } diff --git a/src/common.h b/src/common.h index e320b66..93da70b 100644 --- a/src/common.h +++ b/src/common.h @@ -1,6 +1,7 @@ #pragma once #include <stdlib.h> +#include <utility> struct line_view { const char* line; @@ -8,4 +9,16 @@ struct line_view { }; line_view load_file(const char*); -line_view next_line(line_view); +line_view next_line(line_view, size_t*); + +template <typename F, typename... Args> +void per_line(line_view file, F&& f, Args&&... args) { + size_t offset = 0; + line_view lv; + do { + lv = next_line(file, &offset); + if (!f(lv, std::forward<Args>(args)...)) { + break; + } + } while (offset < file.length); +} |