aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorkaiwu <kaiwu2004@gmail.com>2022-03-14 17:19:04 +0800
committerkaiwu <kaiwu2004@gmail.com>2022-03-14 17:19:04 +0800
commit582cd4c6b680fe9a32ad165b82db34bb60507fea (patch)
tree4838da58ac8e7ec1c0edab89a6fc3f48015ab6ac
parent644663969201ced8e32fe56c7d1fd712d2fa1330 (diff)
downloadadvent-of-code-582cd4c6b680fe9a32ad165b82db34bb60507fea.tar.gz
advent-of-code-582cd4c6b680fe9a32ad165b82db34bb60507fea.zip
next_line
-rw-r--r--src/2015/day1/aoc.cpp13
-rw-r--r--src/2015/day1/aoc.h8
-rw-r--r--src/common.cpp25
-rw-r--r--src/common.h4
-rw-r--r--test/CMakeLists.txt2
5 files changed, 46 insertions, 6 deletions
diff --git a/src/2015/day1/aoc.cpp b/src/2015/day1/aoc.cpp
index e69de29..2263558 100644
--- a/src/2015/day1/aoc.cpp
+++ b/src/2015/day1/aoc.cpp
@@ -0,0 +1,13 @@
+#include "aoc.h"
+
+namespace aoc2015 {
+
+int day1(line_view lv) {
+ int level = 0;
+ for (size_t i = 0; i < lv.length; ++i) {
+ level += lv.line[i] == '(' ? 1 : -1;
+ }
+ return level;
+}
+
+} // namespace aoc2015
diff --git a/src/2015/day1/aoc.h b/src/2015/day1/aoc.h
index 6f70f09..b83b525 100644
--- a/src/2015/day1/aoc.h
+++ b/src/2015/day1/aoc.h
@@ -1 +1,9 @@
#pragma once
+
+#include "common.h"
+
+namespace aoc2015 {
+
+int day1(line_view lv);
+
+}
diff --git a/src/common.cpp b/src/common.cpp
index 8ac3a96..d4457c6 100644
--- a/src/common.cpp
+++ b/src/common.cpp
@@ -5,9 +5,28 @@
#include <sys/stat.h>
line_view load_file(const char* path) {
- return {nullptr, 0};
+ int fd;
+ struct stat fs;
+ fd = open(path, O_RDONLY);
+ if (fd == -1)
+ return {nullptr, 0};
+ if (fstat(fd, &fs) == -1)
+ return {nullptr, 0};
+
+ line_view lv;
+ lv.length = fs.st_size;
+ lv.line = static_cast<const char*>(mmap(NULL, lv.length, PROT_READ, MAP_PRIVATE, fd, 0));
+ return lv;
}
-line_view next_line(const char* file, size_t offset) {
- return {nullptr, 0};
+line_view next_line(line_view file) {
+ static size_t offset = 0;
+ line_view lv;
+ lv.line = file.line + offset;
+ lv.length = 0;
+ while (offset < file.length && file.line[offset] != '\n') {
+ lv.length += 1;
+ offset++;
+ }
+ return lv;
}
diff --git a/src/common.h b/src/common.h
index f242f48..e320b66 100644
--- a/src/common.h
+++ b/src/common.h
@@ -3,9 +3,9 @@
#include <stdlib.h>
struct line_view {
- char* line;
+ const char* line;
size_t length;
};
line_view load_file(const char*);
-line_view next_line(const char*, size_t);
+line_view next_line(line_view);
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index 8b4c564..7410cdd 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -4,7 +4,7 @@ set(TEST_FILES
)
add_executable(aoc ${TEST_FILES})
-target_include_directories(aoc PRIVATE ${PROJECT_SOURCE_DIR}/include)
+target_include_directories(aoc PRIVATE ${PROJECT_SOURCE_DIR}/src)
target_link_libraries(aoc PRIVATE common solution)
add_test(NAME test_aoc COMMAND aoc)