From 8b360ab9fc9d5f3a06dbc74bc8f81d26f07b9ba9 Mon Sep 17 00:00:00 2001 From: Amar Mahmutbegovic Date: Wed, 2 Apr 2025 23:02:38 +0200 Subject: [PATCH] add Chapter03 --- Chapter03/google_test_example.cpp | 91 +++++++++++++++++++++++++++++++ Chapter03/out_of_bound.cpp | 7 +++ Chapter03/uninitialized_value.cpp | 13 +++++ 3 files changed, 111 insertions(+) create mode 100644 Chapter03/google_test_example.cpp create mode 100644 Chapter03/out_of_bound.cpp create mode 100644 Chapter03/uninitialized_value.cpp diff --git a/Chapter03/google_test_example.cpp b/Chapter03/google_test_example.cpp new file mode 100644 index 0000000..fa050a9 --- /dev/null +++ b/Chapter03/google_test_example.cpp @@ -0,0 +1,91 @@ +#include + +#include + +#include "gtest/gtest.h" + +template struct ring_buffer { + + std::array arr; + + std::size_t write_idx = 0; + + std::size_t read_idx = 0; + + std::size_t count = 0; + + void push(T t) { + + arr.at(write_idx) = t; + + write_idx = (write_idx + 1) % N; + + if (count < N) { + + count++; + + } else { + + read_idx = (read_idx + 1) % N; + } + } + + T pop() { + + if (count == 0) { + + return T{}; + } + + T value = arr.at(read_idx); + + read_idx = (read_idx + 1) % N; + + --count; + + return value; + } + + bool is_empty() const { return count == 0; } + + std::size_t get_count() const { return count; } +}; + +TEST(RingBufferInt, PushPop) { + + ring_buffer rb; + + rb.push(1); + + rb.push(2); + + EXPECT_EQ(rb.pop(), 1); + + EXPECT_EQ(rb.pop(), 2); +} + +TEST(RingBufferInt, GetCount) { + + ring_buffer rb; + + for (int i = 0; i < 50; i++) { + + rb.push(i); + } + + EXPECT_EQ(rb.get_count(), 20); + + for (int i = 0; i < 10; i++) { + + rb.pop(); + } + + EXPECT_EQ(rb.get_count(), 10); +} + +int main() { + + testing::InitGoogleTest(); + + return RUN_ALL_TESTS(); +} diff --git a/Chapter03/out_of_bound.cpp b/Chapter03/out_of_bound.cpp new file mode 100644 index 0000000..c5efbc6 --- /dev/null +++ b/Chapter03/out_of_bound.cpp @@ -0,0 +1,7 @@ +#include + +int main() { + std::array arr{1, 2, 3, 4}; + + return arr[4]; +} diff --git a/Chapter03/uninitialized_value.cpp b/Chapter03/uninitialized_value.cpp new file mode 100644 index 0000000..3c4b6c0 --- /dev/null +++ b/Chapter03/uninitialized_value.cpp @@ -0,0 +1,13 @@ +#include + +int sum(const std::array &arr) { + + int ret; + + for(int elem: arr) { + ret += elem; + } + + return ret; + +}