u01: Init

This commit is contained in:
Simon Bruder 2023-04-21 22:46:18 +02:00
parent 636270bbdd
commit 48cfafc9a3
6 changed files with 113 additions and 0 deletions

View file

@ -9,6 +9,20 @@
pkgs = import nixpkgs { inherit system; };
in
{
packages = rec {
u01 = pkgs.callPackage
({ stdenv, catch2_3, cmake }: stdenv.mkDerivation {
name = "ecg-u01";
src = ./u01;
nativeBuildInputs = [ catch2_3 cmake ];
doCheck = true;
})
{ };
};
devShells.default = pkgs.mkShell {
nativeBuildInputs = with pkgs; [ catch2_3 cmake ];
};

19
u01/CMakeLists.txt Normal file
View file

@ -0,0 +1,19 @@
cmake_minimum_required(VERSION 3.20)
project(ecg-u01)
add_library(ecg_tree SHARED node.cpp)
add_executable(main main.cpp)
target_link_libraries(main ecg_tree)
find_package(Catch2 3)
if(Catch2_FOUND)
add_executable(tests tests.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2WithMain ecg_tree)
include(CTest)
include(Catch)
catch_discover_tests(tests)
endif()
install(TARGETS main)
install(TARGETS ecg_tree DESTINATION lib)

8
u01/main.cpp Normal file
View file

@ -0,0 +1,8 @@
#include "node.h"
int main(int argc, char **argv) {
node *root = new node("root");
root->add_child(new node("left child"));
root->add_child(new node("right child"));
delete root;
}

19
u01/node.cpp Normal file
View file

@ -0,0 +1,19 @@
#include <iostream>
#include "node.h"
node::~node() {
for (node *child : children) {
delete child;
}
}
std::string node::get_name() const { return name; }
void node::set_name(const std::string new_name) { this->name = new_name; }
unsigned int node::get_nr_children() const { return children.size(); }
node *node::get_child(std::size_t i) const { return children[i]; }
void node::add_child(node *child) { children.push_back(child); }

18
u01/node.h Normal file
View file

@ -0,0 +1,18 @@
#include <memory>
#include <string>
#include <vector>
class node {
public:
node(const std::string &name);
virtual ~node();
std::string get_name() const;
void set_name(const std::string new_name);
unsigned int get_nr_children() const;
node *get_child(std::size_t i) const;
void add_child(node *child);
private:
std::string name;
std::vector<node *> children;
};

35
u01/tests.cpp Normal file
View file

@ -0,0 +1,35 @@
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include "node.h"
TEST_CASE("Name") {
node *n = new node("test");
REQUIRE(n->get_name() == "test");
n->set_name("foo");
REQUIRE(n->get_name() == "foo");
delete n;
}
TEST_CASE("Number of children") {
node *n = new node("test");
REQUIRE(n->get_nr_children() == 0);
for (std::size_t i = 0; i < 20; i++) {
node *child = new node("child");
n->add_child(child);
}
REQUIRE(n->get_nr_children() == 20);
delete n;
}
TEST_CASE("Get children") {
node *n = new node("test");
REQUIRE(n->get_nr_children() == 0);
for (std::size_t i = 0; i < 5; i++) {
n->add_child(new node("child " + std::to_string(i)));
}
for (std::size_t i = 0; i < 5; i++) {
REQUIRE(n->get_child(i)->get_name() == "child " + std::to_string(i));
}
delete n;
}