From 61d3e7d3f8fcd214f421133b3d55dfd61810cc81 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 10 Oct 2020 21:14:36 +0300 Subject: [PATCH 01/65] Added .DS_Store to .gitignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 259148f..01e14e9 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ *.exe *.out *.app + +# Macos things +*.DS_Store From eace29b37ed9a118969937224df41393ddd94727 Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 10 Oct 2020 21:30:51 +0300 Subject: [PATCH 02/65] updated gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 01e14e9..030bd06 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ # Macos things *.DS_Store +*.idea/ From 43ff0721218e3f9eb9739f1df93579abc5fc2d8f Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 10 Oct 2020 21:32:15 +0300 Subject: [PATCH 03/65] Updated gitignore: --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 030bd06..f3b51ca 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ # Macos things *.DS_Store *.idea/ +*cmake-build-debug From e195f9d911bbd2b16d9bbecb15d63d8d6315e74c Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 10 Oct 2020 21:34:01 +0300 Subject: [PATCH 04/65] Initial project version --- iz1/CMakeLists.txt | 6 ++++++ iz1/main.c | 7 +++++++ 2 files changed, 13 insertions(+) create mode 100644 iz1/CMakeLists.txt create mode 100644 iz1/main.c diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt new file mode 100644 index 0000000..e230893 --- /dev/null +++ b/iz1/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.17) +project(iz1 C) + +set(CMAKE_C_STANDARD 11) + +add_executable(iz1 main.c) \ No newline at end of file diff --git a/iz1/main.c b/iz1/main.c new file mode 100644 index 0000000..7d38eaf --- /dev/null +++ b/iz1/main.c @@ -0,0 +1,7 @@ +#include + +int main() +{ + printf("Hello, World!\n"); + return 0; +} From 3808cc817c69b3ea40967ea33e2b0abdc1c88b0a Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 11 Oct 2020 16:41:14 +0300 Subject: [PATCH 05/65] Updated project structure --- .travis.yml | 14 +++++++++ iz1/CMakeLists.txt | 2 +- iz1/include/html_tag.h | 37 +++++++++++++++++++++++ iz1/include/html_tag_attribute.h | 34 +++++++++++++++++++++ iz1/include/str_mem.h | 21 +++++++++++++ iz1/main.c | 7 ----- iz1/src/html_tag.c | 51 ++++++++++++++++++++++++++++++++ iz1/src/html_tag_attribute.c | 44 +++++++++++++++++++++++++++ iz1/src/main.c | 13 ++++++++ iz1/src/str_mem.c | 50 +++++++++++++++++++++++++++++++ 10 files changed, 265 insertions(+), 8 deletions(-) create mode 100644 .travis.yml create mode 100644 iz1/include/html_tag.h create mode 100644 iz1/include/html_tag_attribute.h create mode 100644 iz1/include/str_mem.h delete mode 100644 iz1/main.c create mode 100644 iz1/src/html_tag.c create mode 100644 iz1/src/html_tag_attribute.c create mode 100644 iz1/src/main.c create mode 100644 iz1/src/str_mem.c diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..01abc62 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,14 @@ +dist: trusty # используем Ubuntu 14.04 Trusty Tahr (а не 12.02 Precise Pangolin) +sudo: required # используем Virtual Machine (а не Docker container) + +language: cpp # на практике разницы между специфичным для C++ окружением + # и, скажем, python -- никакой. Но пусть будет cpp. + +os: + - osx + +compiler: + - clang +install: + # скрипт настройки среды и установки зависимостей: + - source ci/travis/install-$TRAVIS_OS_NAME.sh diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index e230893..53ca937 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -3,4 +3,4 @@ project(iz1 C) set(CMAKE_C_STANDARD 11) -add_executable(iz1 main.c) \ No newline at end of file +add_executable(iz1 src/main.c src/html_tag.c include/html_tag.h src/str_mem.c include/str_mem.h src/html_tag_attribute.c include/html_tag_attribute.h) \ No newline at end of file diff --git a/iz1/include/html_tag.h b/iz1/include/html_tag.h new file mode 100644 index 0000000..c045cbd --- /dev/null +++ b/iz1/include/html_tag.h @@ -0,0 +1,37 @@ +/* + * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» + * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на + * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + * + * Примеры тегов + * + * + * + * + * + * + */ + +#ifndef IZ1_HTML_TAG_H +#define IZ1_HTML_TAG_H + +#include +#include + +#include "html_tag_attribute.h" + +typedef struct +{ + char *name; + bool is_opening; + tag_attr *attributes; +} html_tag; + +html_tag *parse_tag(const char *str); + +int parse_status(const char *str, html_tag *tag); + +int parse_name(const char *str, html_tag *tag); + + +#endif //IZ1_HTML_TAG_H diff --git a/iz1/include/html_tag_attribute.h b/iz1/include/html_tag_attribute.h new file mode 100644 index 0000000..b7b12c7 --- /dev/null +++ b/iz1/include/html_tag_attribute.h @@ -0,0 +1,34 @@ +// +// Created by Pavel Cheklin on 11/10/2020. +// + +#ifndef IZ1_HTML_TAG_ATTRIBUTE_H +#define IZ1_HTML_TAG_ATTRIBUTE_H + +#include + +typedef struct +{ + char *name; + char *value; +} tag_attr; + +typedef struct +{ + tag_attr *data; + size_t size; + size_t _allocated; +} tag_attr_arr; + +// Tag attribute create/delete +void free_attr(tag_attr *attr); + +// Tag attribute array create/delete +void free_attr_arr(tag_attr_arr *arr); + +int parse_attr_count(const char *str); + +int parse_attr(const char *str, tag_attr *attr); + + +#endif //IZ1_HTML_TAG_ATTRIBUTE_H diff --git a/iz1/include/str_mem.h b/iz1/include/str_mem.h new file mode 100644 index 0000000..7dcafb2 --- /dev/null +++ b/iz1/include/str_mem.h @@ -0,0 +1,21 @@ +// +// Created by Pavel Cheklin on 10/10/2020. +// + +#ifndef IZ1_STR_MEM_H +#define IZ1_STR_MEM_H + +#include +#include + +int str_create_copy(char **to_allocate, const char *to_copy); + +int str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); + +int str_find(const char *str, char c); + +int str_first_char_occurence(const char *str, const char *c); + +int str_count(const char *str, char c); + +#endif //IZ1_STR_MEM_H diff --git a/iz1/main.c b/iz1/main.c deleted file mode 100644 index 7d38eaf..0000000 --- a/iz1/main.c +++ /dev/null @@ -1,7 +0,0 @@ -#include - -int main() -{ - printf("Hello, World!\n"); - return 0; -} diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c new file mode 100644 index 0000000..2d97fa0 --- /dev/null +++ b/iz1/src/html_tag.c @@ -0,0 +1,51 @@ +#include "../include/html_tag.h" + +#include "../include/str_mem.h" + +html_tag *parse_tag(const char *str) +{ + html_tag *tag = (html_tag *)malloc(sizeof(html_tag)); + + if (tag == NULL) + return NULL; + + while (*str != '>' && *str != '\0') + { + ++str; + } + + return tag; +} + +int parse_status(const char *str, html_tag *tag) +{ + int i = 0; + if (str[i] != '<') + { + ++i; + if (str[i + 1] == '/') + { + tag->is_opening = false; + ++i; + } + else + tag->is_opening = true; + } + return i; +} + +int parse_name(const char *str, html_tag *tag) +{ + int i = str_find(str, ' '); + str_create_ncopy(&tag->name, str, i); + return i; +} + +int parse_attribute(const char *str, html_tag *tag) +{ + int eq_pos = str_find(str, '='); + int end_pos = str_find(str + eq_pos + 2, '"'); + + return i; +}; + diff --git a/iz1/src/html_tag_attribute.c b/iz1/src/html_tag_attribute.c new file mode 100644 index 0000000..5697113 --- /dev/null +++ b/iz1/src/html_tag_attribute.c @@ -0,0 +1,44 @@ +#include "../include/html_tag_attribute.h" + +#include "../include/str_mem.h" + +// Tag attribute create/delete +void free_attr(tag_attr *attr) +{ + free(attr->name); + free(attr->value); +} + +// Tag attribute array create/delete +void free_attr_arr(tag_attr_arr *arr) +{ + for (int i = 0; i < arr->size; ++i) + free_attr(arr->data + i); + arr->size = 0; + arr->_allocated = 0; +} + +// attr_parsing func +int parse_attr_count(const char *str) +{ + return str_count(str, '='); +} + +int parse_attr(const char *str, tag_attr *attr) +{ + int attr_name_end = str_find(str, '='); + int attr_value_end = str_find(str + attr_name_end + 2, '"'); + + if (str_create_ncopy(&attr->name, + str, + attr_name_end) != EXIT_SUCCESS) + return EXIT_FAILURE; + + if (str_create_ncopy(&attr->name, + str + attr_name_end, + attr_value_end - attr_name_end + 1) != EXIT_SUCCESS) + return EXIT_FAILURE; + + return EXIT_SUCCESS; +} + diff --git a/iz1/src/main.c b/iz1/src/main.c new file mode 100644 index 0000000..2708bde --- /dev/null +++ b/iz1/src/main.c @@ -0,0 +1,13 @@ +/* + * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» + * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на + * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + */ +#include + + +int main() +{ + printf("Hello, World!\n"); + return 0; +} diff --git a/iz1/src/str_mem.c b/iz1/src/str_mem.c new file mode 100644 index 0000000..18957de --- /dev/null +++ b/iz1/src/str_mem.c @@ -0,0 +1,50 @@ +#include "../include/str_mem.h" + +int str_create_copy(char **to_allocate, const char *to_copy) +{ + *to_allocate = (char *)malloc(strlen(to_copy)); + + if (to_allocate == NULL) + return EXIT_FAILURE; + + strcpy(*to_allocate, to_copy); + + return EXIT_SUCCESS; +} + +int str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) +{ + *to_allocate = (char *)malloc(strlen(to_copy)); + + if (to_allocate == NULL) + return EXIT_FAILURE; + + for (int i = 0; i < n && to_copy[i] != '\0'; ++i) + (*to_allocate)[i] = to_copy[i]; + + return EXIT_SUCCESS; +} + +int str_find(const char *str, char c) +{ + int i = 0; + while (str[i] != c && str[i] != '\0') + ++i; + return str[i] == c ? i : -1; +} + +int str_first_char_occurence(const char *str, const char *c) +{ + int i = 0; + while (str_find(c, str[i]) && str[i] != '\0') + ++i; + return i; +} + +int str_count(const char *str, char c) +{ + int count = 0; + while (*str != '\0') + count += (*(str++) == c); + return count; +} From 16a4f8be1d7eae52a210e34d370531580a4d5677 Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 11 Oct 2020 17:11:33 +0300 Subject: [PATCH 06/65] Tag name parsing addded --- iz1/src/html_tag.c | 12 +++++------- iz1/src/main.c | 9 ++++++++- iz1/src/str_mem.c | 10 +++++++--- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c index 2d97fa0..2e823d8 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/html_tag.c @@ -9,10 +9,8 @@ html_tag *parse_tag(const char *str) if (tag == NULL) return NULL; - while (*str != '>' && *str != '\0') - { - ++str; - } + str += parse_status(str, tag); + parse_name(str, tag); return tag; } @@ -20,7 +18,7 @@ html_tag *parse_tag(const char *str) int parse_status(const char *str, html_tag *tag) { int i = 0; - if (str[i] != '<') + if (str[i] == '<') { ++i; if (str[i + 1] == '/') @@ -36,7 +34,7 @@ int parse_status(const char *str, html_tag *tag) int parse_name(const char *str, html_tag *tag) { - int i = str_find(str, ' '); + int i = str_first_char_occurence(str, " >"); str_create_ncopy(&tag->name, str, i); return i; } @@ -46,6 +44,6 @@ int parse_attribute(const char *str, html_tag *tag) int eq_pos = str_find(str, '='); int end_pos = str_find(str + eq_pos + 2, '"'); - return i; + return end_pos; }; diff --git a/iz1/src/main.c b/iz1/src/main.c index 2708bde..24239b7 100644 --- a/iz1/src/main.c +++ b/iz1/src/main.c @@ -5,9 +5,16 @@ */ #include +#include "../include/html_tag.h" + +#define MAX_STR_LEN 256 int main() { - printf("Hello, World!\n"); + char line[MAX_STR_LEN] = ""; +// fgets(line, MAX_STR_LEN, stdin); + html_tag *tag = parse_tag(line); + printf("line = '%s'\n", line); + printf("Tag:\nname: \t\t'%s'\nis_opening: \t'%d'\n", tag->name, tag->is_opening); return 0; } diff --git a/iz1/src/str_mem.c b/iz1/src/str_mem.c index 18957de..caf499b 100644 --- a/iz1/src/str_mem.c +++ b/iz1/src/str_mem.c @@ -14,14 +14,18 @@ int str_create_copy(char **to_allocate, const char *to_copy) int str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) { - *to_allocate = (char *)malloc(strlen(to_copy)); + size_t allocate_size = (strlen(to_copy) > n ? n : strlen(to_copy)) + 1; + *to_allocate = (char *)malloc(allocate_size); if (to_allocate == NULL) return EXIT_FAILURE; - for (int i = 0; i < n && to_copy[i] != '\0'; ++i) + int i; + for (i = 0; i < n && to_copy[i] != '\0'; ++i) (*to_allocate)[i] = to_copy[i]; + (*to_allocate)[i] = '\0'; + return EXIT_SUCCESS; } @@ -36,7 +40,7 @@ int str_find(const char *str, char c) int str_first_char_occurence(const char *str, const char *c) { int i = 0; - while (str_find(c, str[i]) && str[i] != '\0') + while (str_find(c, str[i]) == -1 && str[i] != '\0') ++i; return i; } From 77b78bb455b2caa8ed18995680467c0503527852 Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 11 Oct 2020 17:20:23 +0300 Subject: [PATCH 07/65] Updated ci --- .travis.yml | 21 +++++++++++++++------ iz1/CMakeLists.txt | 8 +++++++- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index 01abc62..fb37e79 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,14 +1,23 @@ dist: trusty # используем Ubuntu 14.04 Trusty Tahr (а не 12.02 Precise Pangolin) sudo: required # используем Virtual Machine (а не Docker container) -language: cpp # на практике разницы между специфичным для C++ окружением +language: c # на практике разницы между специфичным для C++ окружением # и, скажем, python -- никакой. Но пусть будет cpp. os: - - osx + -linux compiler: - - clang -install: - # скрипт настройки среды и установки зависимостей: - - source ci/travis/install-$TRAVIS_OS_NAME.sh + -gcc + +script: + # скрипт сборки и тестирования проекта: + - cd iz1 + - mkdir build + - cd build + - cmake .. + - make + +after_script: + - make clean + diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 53ca937..e4828fc 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -3,4 +3,10 @@ project(iz1 C) set(CMAKE_C_STANDARD 11) -add_executable(iz1 src/main.c src/html_tag.c include/html_tag.h src/str_mem.c include/str_mem.h src/html_tag_attribute.c include/html_tag_attribute.h) \ No newline at end of file +add_executable(iz1 src/main.c + src/html_tag.c + include/html_tag.h + src/str_mem.c + include/str_mem.h + src/html_tag_attribute.c + include/html_tag_attribute.h) \ No newline at end of file From 50993ff923ceaf49b0ff27eec0b0242e48c2d2aa Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 11 Oct 2020 17:22:17 +0300 Subject: [PATCH 08/65] Updated cmake version --- iz1/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index e4828fc..7f076a9 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.17) +cmake_minimum_required(VERSION 3.5) project(iz1 C) set(CMAKE_C_STANDARD 11) From f90e1d0d1675ec249627da6270afc31d8f0ba97f Mon Sep 17 00:00:00 2001 From: Paul Date: Sun, 11 Oct 2020 20:59:29 +0300 Subject: [PATCH 09/65] Added gtest initial --- iz1/CMakeLists.txt | 44 ++++++++++++++++++++++++++++++----------- iz1/CMakeLists.txt.in | 15 ++++++++++++++ iz1/src/html_tag.c | 3 +-- iz1/test/CMakeLists.txt | 18 +++++++++++++++++ iz1/test/main.cpp | 6 ++++++ 5 files changed, 72 insertions(+), 14 deletions(-) create mode 100644 iz1/CMakeLists.txt.in create mode 100644 iz1/test/CMakeLists.txt create mode 100644 iz1/test/main.cpp diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 7f076a9..9bd8267 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -1,12 +1,32 @@ -cmake_minimum_required(VERSION 3.5) -project(iz1 C) - -set(CMAKE_C_STANDARD 11) - -add_executable(iz1 src/main.c - src/html_tag.c - include/html_tag.h - src/str_mem.c - include/str_mem.h - src/html_tag_attribute.c - include/html_tag_attribute.h) \ No newline at end of file +cmake_minimum_required(VERSION 3.1) + +project(iz1) + +## +### Test definitions ### +## + +configure_file(CMakeLists.txt.in + googletest-download/CMakeLists.txt) +execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) +execute_process(COMMAND ${CMAKE_COMMAND} --build . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) + +add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src + ${CMAKE_BINARY_DIR}/googletest-build) + +enable_testing() +add_subdirectory(test) + +## +### Source definitions ### +## + +include_directories("${PROJECT_SOURCE_DIR}/include") + +file(GLOB sources + "${PROJECT_SOURCE_DIR}/include/*.h" + "${PROJECT_SOURCE_DIR}/src/*.c") + +add_executable(iz1 ${sources}) \ No newline at end of file diff --git a/iz1/CMakeLists.txt.in b/iz1/CMakeLists.txt.in new file mode 100644 index 0000000..586d9d6 --- /dev/null +++ b/iz1/CMakeLists.txt.in @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.1) + +project(googletest-download NONE) + +include(ExternalProject) +ExternalProject_Add(googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.8.1 + SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" + BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" +) \ No newline at end of file diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c index 2e823d8..42fb54e 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/html_tag.c @@ -45,5 +45,4 @@ int parse_attribute(const char *str, html_tag *tag) int end_pos = str_find(str + eq_pos + 2, '"'); return end_pos; -}; - +}; \ No newline at end of file diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt new file mode 100644 index 0000000..2804405 --- /dev/null +++ b/iz1/test/CMakeLists.txt @@ -0,0 +1,18 @@ +include_directories("${PROJECT_SOURCE_DIR}/include") + +file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") +list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") + +file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") +list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") + +foreach(file ${tests}) + set(name) + get_filename_component(name ${file} NAME_WE) + add_executable("${name}_tests" + ${sources} + ${file} + "${PROJECT_SOURCE_DIR}/test/main.cpp") + target_link_libraries("${name}_tests" gtest_main) + add_test(NAME ${name} COMMAND "${name}_tests") +endforeach() \ No newline at end of file diff --git a/iz1/test/main.cpp b/iz1/test/main.cpp new file mode 100644 index 0000000..b42b721 --- /dev/null +++ b/iz1/test/main.cpp @@ -0,0 +1,6 @@ +#include "gtest/gtest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file From bf48262db2fd84062d69b88a8870ecb9732e9541 Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:29:07 +0300 Subject: [PATCH 10/65] Working attribute parser --- iz1/CMakeLists.txt | 5 +- iz1/include/html_tag/attr.h | 22 +++++++++ iz1/include/{html_tag.h => html_tag/tag.h} | 9 ++-- iz1/include/html_tag_attribute.h | 34 -------------- iz1/include/my_str/alg.h | 14 ++++++ iz1/include/my_str/mem.h | 19 ++++++++ iz1/include/str_mem.h | 21 --------- iz1/src/alg.c | 25 ++++++++++ iz1/src/attr.c | 29 ++++++++++++ iz1/src/html_tag_attribute.c | 44 ------------------ iz1/src/main.c | 4 +- iz1/src/mem.c | 30 ++++++++++++ iz1/src/str_mem.c | 54 ---------------------- iz1/src/{html_tag.c => tag.c} | 20 +------- iz1/test/CMakeLists.txt | 2 +- iz1/test/attr.cpp | 42 +++++++++++++++++ 16 files changed, 193 insertions(+), 181 deletions(-) create mode 100644 iz1/include/html_tag/attr.h rename iz1/include/{html_tag.h => html_tag/tag.h} (87%) delete mode 100644 iz1/include/html_tag_attribute.h create mode 100644 iz1/include/my_str/alg.h create mode 100644 iz1/include/my_str/mem.h delete mode 100644 iz1/include/str_mem.h create mode 100644 iz1/src/alg.c create mode 100644 iz1/src/attr.c delete mode 100644 iz1/src/html_tag_attribute.c create mode 100644 iz1/src/mem.c delete mode 100644 iz1/src/str_mem.c rename iz1/src/{html_tag.c => tag.c} (53%) create mode 100644 iz1/test/attr.cpp diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 9bd8267..2e5c728 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -26,7 +26,8 @@ add_subdirectory(test) include_directories("${PROJECT_SOURCE_DIR}/include") file(GLOB sources - "${PROJECT_SOURCE_DIR}/include/*.h" + "${PROJECT_SOURCE_DIR}/include/html_tag/*.h" + "${PROJECT_SOURCE_DIR}/include/my_str/*.h" "${PROJECT_SOURCE_DIR}/src/*.c") -add_executable(iz1 ${sources}) \ No newline at end of file +add_executable(iz1 ${sources} include/my_str/alg.h src/alg.c) \ No newline at end of file diff --git a/iz1/include/html_tag/attr.h b/iz1/include/html_tag/attr.h new file mode 100644 index 0000000..4af6924 --- /dev/null +++ b/iz1/include/html_tag/attr.h @@ -0,0 +1,22 @@ +// +// Created by Pavel Cheklin on 11/10/2020. +// + +#ifndef IZ1_ATTR_H +#define IZ1_ATTR_H + +#include + +typedef struct +{ + char *name; + char *value; +} tag_attr; + + +void free_attr(tag_attr *attr); + +tag_attr *parse_attr(const char *str, int *attr_end ); + + +#endif //IZ1_ATTR_H diff --git a/iz1/include/html_tag.h b/iz1/include/html_tag/tag.h similarity index 87% rename from iz1/include/html_tag.h rename to iz1/include/html_tag/tag.h index c045cbd..73bc1e6 100644 --- a/iz1/include/html_tag.h +++ b/iz1/include/html_tag/tag.h @@ -12,13 +12,13 @@ * */ -#ifndef IZ1_HTML_TAG_H -#define IZ1_HTML_TAG_H +#ifndef IZ1_TAG_H +#define IZ1_TAG_H #include #include -#include "html_tag_attribute.h" +#include "attr.h" typedef struct { @@ -31,7 +31,6 @@ html_tag *parse_tag(const char *str); int parse_status(const char *str, html_tag *tag); -int parse_name(const char *str, html_tag *tag); -#endif //IZ1_HTML_TAG_H +#endif //IZ1_TAG_H diff --git a/iz1/include/html_tag_attribute.h b/iz1/include/html_tag_attribute.h deleted file mode 100644 index b7b12c7..0000000 --- a/iz1/include/html_tag_attribute.h +++ /dev/null @@ -1,34 +0,0 @@ -// -// Created by Pavel Cheklin on 11/10/2020. -// - -#ifndef IZ1_HTML_TAG_ATTRIBUTE_H -#define IZ1_HTML_TAG_ATTRIBUTE_H - -#include - -typedef struct -{ - char *name; - char *value; -} tag_attr; - -typedef struct -{ - tag_attr *data; - size_t size; - size_t _allocated; -} tag_attr_arr; - -// Tag attribute create/delete -void free_attr(tag_attr *attr); - -// Tag attribute array create/delete -void free_attr_arr(tag_attr_arr *arr); - -int parse_attr_count(const char *str); - -int parse_attr(const char *str, tag_attr *attr); - - -#endif //IZ1_HTML_TAG_ATTRIBUTE_H diff --git a/iz1/include/my_str/alg.h b/iz1/include/my_str/alg.h new file mode 100644 index 0000000..1ea10a8 --- /dev/null +++ b/iz1/include/my_str/alg.h @@ -0,0 +1,14 @@ +// +// Created by Pavel Cheklin on 11/10/2020. +// + +#ifndef IZ1_ALG_H +#define IZ1_ALG_H + +int str_find(const char *str, char c); + +int str_first_char_occurence(const char *str, const char *c); + +int str_count(const char *str, char c); + +#endif //IZ1_ALG_H diff --git a/iz1/include/my_str/mem.h b/iz1/include/my_str/mem.h new file mode 100644 index 0000000..35a1287 --- /dev/null +++ b/iz1/include/my_str/mem.h @@ -0,0 +1,19 @@ +// +// Created by Pavel Cheklin on 10/10/2020. +// + +#ifndef IZ1_MEM_H +#define IZ1_MEM_H + +#include +#include + + +size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); + +size_t str_create_copy(char **to_allocate, const char *to_copy); + +size_t str_create_word(char **to_allocate, const char *src, char word_end); + + +#endif //IZ1_MEM_H diff --git a/iz1/include/str_mem.h b/iz1/include/str_mem.h deleted file mode 100644 index 7dcafb2..0000000 --- a/iz1/include/str_mem.h +++ /dev/null @@ -1,21 +0,0 @@ -// -// Created by Pavel Cheklin on 10/10/2020. -// - -#ifndef IZ1_STR_MEM_H -#define IZ1_STR_MEM_H - -#include -#include - -int str_create_copy(char **to_allocate, const char *to_copy); - -int str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); - -int str_find(const char *str, char c); - -int str_first_char_occurence(const char *str, const char *c); - -int str_count(const char *str, char c); - -#endif //IZ1_STR_MEM_H diff --git a/iz1/src/alg.c b/iz1/src/alg.c new file mode 100644 index 0000000..a5a0afb --- /dev/null +++ b/iz1/src/alg.c @@ -0,0 +1,25 @@ +#include "my_str/alg.h" + +int str_find(const char *str, char c) +{ + int i = 0; + while (str[i] != c && str[i] != '\0') + ++i; + return i; // str[i] == c ? i : -1; +} + +int str_first_char_occurence(const char *str, const char *c) +{ + int i = 0; + while (str_find(c, str[i]) == -1 && str[i] != '\0') + ++i; + return i; +} + +int str_count(const char *str, char c) +{ + int count = 0; + while (*str != '\0') + count += (*(str++) == c); + return count; +} diff --git a/iz1/src/attr.c b/iz1/src/attr.c new file mode 100644 index 0000000..5f86aca --- /dev/null +++ b/iz1/src/attr.c @@ -0,0 +1,29 @@ +#include "html_tag/attr.h" + +#include + +#include "my_str/mem.h" + +// Tag attribute create/delete +void free_attr(tag_attr *attr) +{ + free(attr->name); + free(attr->value); +} + +tag_attr *parse_attr(const char *str, int *attr_end) +{ + const char *str_start = str; + tag_attr *attr = (tag_attr *) malloc(sizeof(tag_attr)); + + str += str_create_word(&attr->name, str, '='); + if (*str == '"') + str += str_create_word(&attr->value, str + 1, '"'); + else + str += str_create_word(&attr->value, str, ' '); + + ptrdiff_t attr_end_ = str - str_start; + *attr_end -= (int)(attr_end_); + + return attr; +} \ No newline at end of file diff --git a/iz1/src/html_tag_attribute.c b/iz1/src/html_tag_attribute.c deleted file mode 100644 index 5697113..0000000 --- a/iz1/src/html_tag_attribute.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../include/html_tag_attribute.h" - -#include "../include/str_mem.h" - -// Tag attribute create/delete -void free_attr(tag_attr *attr) -{ - free(attr->name); - free(attr->value); -} - -// Tag attribute array create/delete -void free_attr_arr(tag_attr_arr *arr) -{ - for (int i = 0; i < arr->size; ++i) - free_attr(arr->data + i); - arr->size = 0; - arr->_allocated = 0; -} - -// attr_parsing func -int parse_attr_count(const char *str) -{ - return str_count(str, '='); -} - -int parse_attr(const char *str, tag_attr *attr) -{ - int attr_name_end = str_find(str, '='); - int attr_value_end = str_find(str + attr_name_end + 2, '"'); - - if (str_create_ncopy(&attr->name, - str, - attr_name_end) != EXIT_SUCCESS) - return EXIT_FAILURE; - - if (str_create_ncopy(&attr->name, - str + attr_name_end, - attr_value_end - attr_name_end + 1) != EXIT_SUCCESS) - return EXIT_FAILURE; - - return EXIT_SUCCESS; -} - diff --git a/iz1/src/main.c b/iz1/src/main.c index 24239b7..3e1373e 100644 --- a/iz1/src/main.c +++ b/iz1/src/main.c @@ -5,13 +5,13 @@ */ #include -#include "../include/html_tag.h" +#include "html_tag/tag.h" #define MAX_STR_LEN 256 int main() { - char line[MAX_STR_LEN] = ""; + char line[MAX_STR_LEN] = "o>"; // fgets(line, MAX_STR_LEN, stdin); html_tag *tag = parse_tag(line); printf("line = '%s'\n", line); diff --git a/iz1/src/mem.c b/iz1/src/mem.c new file mode 100644 index 0000000..807d202 --- /dev/null +++ b/iz1/src/mem.c @@ -0,0 +1,30 @@ +#include "my_str/mem.h" + +#include "my_str/alg.h" + + +size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) +{ + size_t to_copy_len = strlen(to_copy); + size_t allocate_size = (to_copy_len > n ? n : to_copy_len) + 1; + *to_allocate = (char *) malloc(allocate_size); + int i; + for (i = 0; i < n && to_copy[i] != '\0'; ++i) + (*to_allocate)[i] = to_copy[i]; + + (*to_allocate)[i] = '\0'; + + return allocate_size; +} + +int n(char **to_allocate, const char *to_copy) +{ + size_t len = strlen(to_copy); + return str_create_ncopy(to_allocate, to_copy, len); +} + +size_t str_create_word(char **to_allocate, const char *src, char sep) +{ + int word_end = str_find(src, sep); + return str_create_ncopy(to_allocate, src, word_end); +} diff --git a/iz1/src/str_mem.c b/iz1/src/str_mem.c deleted file mode 100644 index caf499b..0000000 --- a/iz1/src/str_mem.c +++ /dev/null @@ -1,54 +0,0 @@ -#include "../include/str_mem.h" - -int str_create_copy(char **to_allocate, const char *to_copy) -{ - *to_allocate = (char *)malloc(strlen(to_copy)); - - if (to_allocate == NULL) - return EXIT_FAILURE; - - strcpy(*to_allocate, to_copy); - - return EXIT_SUCCESS; -} - -int str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) -{ - size_t allocate_size = (strlen(to_copy) > n ? n : strlen(to_copy)) + 1; - *to_allocate = (char *)malloc(allocate_size); - - if (to_allocate == NULL) - return EXIT_FAILURE; - - int i; - for (i = 0; i < n && to_copy[i] != '\0'; ++i) - (*to_allocate)[i] = to_copy[i]; - - (*to_allocate)[i] = '\0'; - - return EXIT_SUCCESS; -} - -int str_find(const char *str, char c) -{ - int i = 0; - while (str[i] != c && str[i] != '\0') - ++i; - return str[i] == c ? i : -1; -} - -int str_first_char_occurence(const char *str, const char *c) -{ - int i = 0; - while (str_find(c, str[i]) == -1 && str[i] != '\0') - ++i; - return i; -} - -int str_count(const char *str, char c) -{ - int count = 0; - while (*str != '\0') - count += (*(str++) == c); - return count; -} diff --git a/iz1/src/html_tag.c b/iz1/src/tag.c similarity index 53% rename from iz1/src/html_tag.c rename to iz1/src/tag.c index 42fb54e..e7aa016 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/tag.c @@ -1,6 +1,6 @@ -#include "../include/html_tag.h" +#include "html_tag/tag.h" -#include "../include/str_mem.h" +#include "my_str/mem.h" html_tag *parse_tag(const char *str) { @@ -10,8 +10,6 @@ html_tag *parse_tag(const char *str) return NULL; str += parse_status(str, tag); - parse_name(str, tag); - return tag; } @@ -32,17 +30,3 @@ int parse_status(const char *str, html_tag *tag) return i; } -int parse_name(const char *str, html_tag *tag) -{ - int i = str_first_char_occurence(str, " >"); - str_create_ncopy(&tag->name, str, i); - return i; -} - -int parse_attribute(const char *str, html_tag *tag) -{ - int eq_pos = str_find(str, '='); - int end_pos = str_find(str + eq_pos + 2, '"'); - - return end_pos; -}; \ No newline at end of file diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt index 2804405..0de9698 100644 --- a/iz1/test/CMakeLists.txt +++ b/iz1/test/CMakeLists.txt @@ -12,7 +12,7 @@ foreach(file ${tests}) add_executable("${name}_tests" ${sources} ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp") + "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp) target_link_libraries("${name}_tests" gtest_main) add_test(NAME ${name} COMMAND "${name}_tests") endforeach() \ No newline at end of file diff --git a/iz1/test/attr.cpp b/iz1/test/attr.cpp new file mode 100644 index 0000000..8726325 --- /dev/null +++ b/iz1/test/attr.cpp @@ -0,0 +1,42 @@ +#include "gtest/gtest.h" +#include + +extern "C" { +#include "html_tag/attr.h" +} + +TEST(correct_input, one_attributе_no_quotes) +{ + char correct_name[] = "attr1"; + char correct_value[] = "value1"; + char line[] = "attr1=value1"; + int attr_end = 0; + tag_attr *attr = parse_attr(line, &attr_end); + ASSERT_EQ(strcmp(attr->name, correct_name), 0); + ASSERT_EQ(strcmp(attr->value, correct_value), 0); + free_attr(attr); +} + +TEST(correct_input, one_attributе_quotes) +{ + char correct_name[] = "attr1"; + char correct_value[] = "value1"; + char line[] = "attr1=\"value1\""; + int attr_end = 0; + tag_attr *attr = parse_attr(line, &attr_end); + ASSERT_EQ(strcmp(attr->name, correct_name), 0); + ASSERT_EQ(strcmp(attr->value, correct_value), 0); + free_attr(attr); +} + +TEST(correct_input, one_attribute_quotes_space) +{ + char correct_name[] = "attr1"; + char correct_value[] = "value1 value2"; + char line[] = "attr1=\"value1 value2\""; + int attr_end = 0; + tag_attr *attr = parse_attr(line, &attr_end); + ASSERT_EQ(strcmp(attr->name, correct_name), 0); + ASSERT_EQ(strcmp(attr->value, correct_value), 0); + free_attr(attr); +} From 77746baaf39b342bd986908231fd44551a69fb60 Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:33:03 +0300 Subject: [PATCH 11/65] Updated ci script --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index fb37e79..98804ab 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,6 +17,8 @@ script: - cd build - cmake .. - make + - cd test + - ctest after_script: - make clean From 9d5dd77b0473c3d0dda6b1c7b3fca8462ffe790b Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:36:51 +0300 Subject: [PATCH 12/65] Updated cmakelists --- iz1/CMakeLists.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 2e5c728..1ef6755 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -2,10 +2,15 @@ cmake_minimum_required(VERSION 3.1) project(iz1) +set(CMAKE_CXX_COMPILER /usr/bin/g++) + +set(CMAKE_C_COMPILER /usr/bin/cc) + ## ### Test definitions ### ## + configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . @@ -30,4 +35,4 @@ file(GLOB sources "${PROJECT_SOURCE_DIR}/include/my_str/*.h" "${PROJECT_SOURCE_DIR}/src/*.c") -add_executable(iz1 ${sources} include/my_str/alg.h src/alg.c) \ No newline at end of file +add_executable(iz1 ${sources} include/my_str/alg.h src/alg.c) From d2128adfba993c0ca88def6042353fadcf663782 Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:45:00 +0300 Subject: [PATCH 13/65] update cmakelists --- iz1/CMakeLists.txt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 1ef6755..174cbed 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -1,16 +1,19 @@ cmake_minimum_required(VERSION 3.1) -project(iz1) +project(iz1 C CXX) + +set (CMAKE_C_STANDARD 99) +set (CMAKE_C_COMPILER /usr/bin/clang) + +set (CMAKE_CXX_STANDARD 17) +set (CMAKE_CXX_COMPILER /usr/bin/clang) -set(CMAKE_CXX_COMPILER /usr/bin/g++) -set(CMAKE_C_COMPILER /usr/bin/cc) ## ### Test definitions ### ## - configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . From 6e06807e4dbf2b1f3a17271ea904db9069f3e71a Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:50:55 +0300 Subject: [PATCH 14/65] updated build line --- .travis.yml | 27 +++++++-------------------- iz1/CMakeLists.txt | 5 ----- 2 files changed, 7 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 98804ab..3ed4e4f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,25 +1,12 @@ -dist: trusty # используем Ubuntu 14.04 Trusty Tahr (а не 12.02 Precise Pangolin) -sudo: required # используем Virtual Machine (а не Docker container) +language: c -language: c # на практике разницы между специфичным для C++ окружением - # и, скажем, python -- никакой. Но пусть будет cpp. - -os: - -linux - -compiler: - -gcc - +sudo: false # only for faster builds script: - # скрипт сборки и тестирования проекта: - cd iz1 - - mkdir build + - mkdir build - cd build - - cmake .. - - make - - cd test - - ctest - -after_script: - - make clean + - cmake .. && make + - cd test && ctest +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 174cbed..df41cc2 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -3,12 +3,7 @@ cmake_minimum_required(VERSION 3.1) project(iz1 C CXX) set (CMAKE_C_STANDARD 99) -set (CMAKE_C_COMPILER /usr/bin/clang) - set (CMAKE_CXX_STANDARD 17) -set (CMAKE_CXX_COMPILER /usr/bin/clang) - - ## ### Test definitions ### From 3d72a0b0afa666fc2453553692757941ad17d3f2 Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 12 Oct 2020 22:55:54 +0300 Subject: [PATCH 15/65] update tests --- iz1/test/attr.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/iz1/test/attr.cpp b/iz1/test/attr.cpp index 8726325..ef76ea6 100644 --- a/iz1/test/attr.cpp +++ b/iz1/test/attr.cpp @@ -5,7 +5,7 @@ extern "C" { #include "html_tag/attr.h" } -TEST(correct_input, one_attributе_no_quotes) +TEST(correct_input, no_quotes) { char correct_name[] = "attr1"; char correct_value[] = "value1"; @@ -17,7 +17,7 @@ TEST(correct_input, one_attributе_no_quotes) free_attr(attr); } -TEST(correct_input, one_attributе_quotes) +TEST(correct_input, quotes_one) { char correct_name[] = "attr1"; char correct_value[] = "value1"; @@ -29,7 +29,7 @@ TEST(correct_input, one_attributе_quotes) free_attr(attr); } -TEST(correct_input, one_attribute_quotes_space) +TEST(correct_input, quotes_two) { char correct_name[] = "attr1"; char correct_value[] = "value1 value2"; From fb52795477b59738b6898a67f0dee464cd381795 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 15:42:06 +0300 Subject: [PATCH 16/65] Added README.MD --- iz1/README.MD | 20 ++++++++++++++++++++ iz1/test/html_tag.cpp | 4 ++++ 2 files changed, 24 insertions(+) create mode 100644 iz1/README.MD create mode 100644 iz1/test/html_tag.cpp diff --git a/iz1/README.MD b/iz1/README.MD new file mode 100644 index 0000000..0b68772 --- /dev/null +++ b/iz1/README.MD @@ -0,0 +1,20 @@ +# Индивидуальное задание 1 + +ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: +* грамотное разбиение проекта на файлы; +* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; +* максимальное покрытие кода юнит-тестами; +* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами +* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью +Вариант #23 +Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + +Требования к оформлению: +Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. +Помимо самой программы необходимо: +– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; +– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. +Внимание: в основной ветке проекта никакого кода быть не должно! +– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; +– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; +– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; diff --git a/iz1/test/html_tag.cpp b/iz1/test/html_tag.cpp new file mode 100644 index 0000000..a3b806f --- /dev/null +++ b/iz1/test/html_tag.cpp @@ -0,0 +1,4 @@ +// +// Created by Pavel Cheklin on 13/10/2020. +// + From 83faa0a84685014b4ee3bc7ed407575ff97c50b6 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 16:02:29 +0300 Subject: [PATCH 17/65] Added correct tests for html_tag{: --- iz1/test/html_tag.cpp | 108 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 105 insertions(+), 3 deletions(-) diff --git a/iz1/test/html_tag.cpp b/iz1/test/html_tag.cpp index a3b806f..c86265a 100644 --- a/iz1/test/html_tag.cpp +++ b/iz1/test/html_tag.cpp @@ -1,4 +1,106 @@ -// -// Created by Pavel Cheklin on 13/10/2020. -// +#include "gtest/gtest.h" +#include +extern "C" { +#include "html_tag/tag.h" +} + +TEST(tag_correct_input, no_quotes) +{ + char src[] = ""; + char expected_name[] = "opening_tag"; + bool expected_opening = true; + size_t expected_attr_count = 1; + char expected_attr_names[][10] = {"attr1"}; + char expected_attr_values[][10] = {"value1"}; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + for (size_t i = 0; i < res->attributes_count; ++i) + { + ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); + ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); + } + free_tag(&res); +} + +TEST(tag_correct_input, quotes_one) +{ + char src[] = ""; + char expected_name[] = "opening_tag"; + bool expected_opening = true; + size_t expected_attr_count = 1; + char expected_attr_names[][10] = {"attr1"}; + char expected_attr_values[][10] = {"value1"}; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + for (size_t i = 0; i < res->attributes_count; ++i) + { + ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); + ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); + } + free_tag(&res); +} + +TEST(tag_correct_input, quotes_two) +{ + char src[] = ""; + char expected_name[] = "opening_tag"; + bool expected_opening = true; + size_t expected_attr_count = 1; + char expected_attr_names[][20] = {"attr1"}; + char expected_attr_values[][20] = {"value1 value2"}; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + for (size_t i = 0; i < res->attributes_count; ++i) + { + ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); + ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); + } + free_tag(&res); +} + + +TEST(tag_correct_input, two_attrs) +{ + char src[] = ""; + char expected_name[] = "opening_tag"; + bool expected_opening = true; + size_t expected_attr_count = 1; + char expected_attr_names[][20] = {"attr1", "attr2"}; + char expected_attr_values[][20] = {"value1 value2", "value3"}; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + for (size_t i = 0; i < res->attributes_count; ++i) + { + ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); + ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); + } + free_tag(&res); +} + + +TEST(tag_correct_input, closing) +{ + char src[] = ""; + char expected_name[] = "closing_tag"; + bool expected_opening = false; + size_t expected_attr_count = 0; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + free_tag(&res); +} From 96563d85ec614c5978d524cda3bd4b2db2f89913 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 17:07:37 +0300 Subject: [PATCH 18/65] updated tests --- iz1/test/CMakeLists.txt | 2 +- iz1/test/attr.cpp | 6 +++--- iz1/test/html_tag.cpp | 23 ++++++++++++++++++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt index 0de9698..e39e463 100644 --- a/iz1/test/CMakeLists.txt +++ b/iz1/test/CMakeLists.txt @@ -12,7 +12,7 @@ foreach(file ${tests}) add_executable("${name}_tests" ${sources} ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp) + "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp html_tag.cpp) target_link_libraries("${name}_tests" gtest_main) add_test(NAME ${name} COMMAND "${name}_tests") endforeach() \ No newline at end of file diff --git a/iz1/test/attr.cpp b/iz1/test/attr.cpp index ef76ea6..24a2402 100644 --- a/iz1/test/attr.cpp +++ b/iz1/test/attr.cpp @@ -14,7 +14,7 @@ TEST(correct_input, no_quotes) tag_attr *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(attr); + free_attr(&attr); } TEST(correct_input, quotes_one) @@ -26,7 +26,7 @@ TEST(correct_input, quotes_one) tag_attr *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(attr); + free_attr(&attr); } TEST(correct_input, quotes_two) @@ -38,5 +38,5 @@ TEST(correct_input, quotes_two) tag_attr *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(attr); + free_attr(&attr); } diff --git a/iz1/test/html_tag.cpp b/iz1/test/html_tag.cpp index c86265a..4eb722c 100644 --- a/iz1/test/html_tag.cpp +++ b/iz1/test/html_tag.cpp @@ -74,7 +74,7 @@ TEST(tag_correct_input, two_attrs) char src[] = ""; char expected_name[] = "opening_tag"; bool expected_opening = true; - size_t expected_attr_count = 1; + size_t expected_attr_count = 2; char expected_attr_names[][20] = {"attr1", "attr2"}; char expected_attr_values[][20] = {"value1 value2", "value3"}; @@ -90,6 +90,27 @@ TEST(tag_correct_input, two_attrs) free_tag(&res); } +TEST(tag_correct_input, three_attrs) +{ + char src[] = R"()"; + char expected_name[] = "opening_tag"; + bool expected_opening = true; + size_t expected_attr_count = 3; + char expected_attr_names[][20] = {"attr1", "attr2", "attr3"}; + char expected_attr_values[][20] = {"value1 value2", "value3", "value4"}; + + html_tag *res = parse_tag(src); + ASSERT_EQ(strcmp(res->name, expected_name), 0); + ASSERT_EQ(res->is_opening, expected_opening); + ASSERT_EQ(res->attributes_count, expected_attr_count); + for (size_t i = 0; i < res->attributes_count; ++i) + { + ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); + ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); + } + free_tag(&res); +} + TEST(tag_correct_input, closing) { From 5deef8a5c1c165eac9e790083ef7cba632ddb4c2 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 17:09:04 +0300 Subject: [PATCH 19/65] tag parsing version added --- iz1/CMakeLists.txt | 2 +- iz1/include/html_tag/attr.h | 6 +++--- iz1/include/html_tag/tag.h | 7 +++++-- iz1/include/my_str/mem.h | 2 +- iz1/src/alg.c | 4 +++- iz1/src/attr.c | 30 ++++++++++++++++++++++-------- iz1/src/mem.c | 4 ++-- iz1/src/tag.c | 24 +++++++++++++++++++----- 8 files changed, 56 insertions(+), 23 deletions(-) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index df41cc2..42c4756 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -33,4 +33,4 @@ file(GLOB sources "${PROJECT_SOURCE_DIR}/include/my_str/*.h" "${PROJECT_SOURCE_DIR}/src/*.c") -add_executable(iz1 ${sources} include/my_str/alg.h src/alg.c) +add_executable(iz1 ${sources} ) diff --git a/iz1/include/html_tag/attr.h b/iz1/include/html_tag/attr.h index 4af6924..e2c26a2 100644 --- a/iz1/include/html_tag/attr.h +++ b/iz1/include/html_tag/attr.h @@ -13,10 +13,10 @@ typedef struct char *value; } tag_attr; +tag_attr *parse_attr(const char *str, int *attr_end); -void free_attr(tag_attr *attr); - -tag_attr *parse_attr(const char *str, int *attr_end ); +tag_attr **parse_attr_arr(const char *str, size_t count); +void free_attr(tag_attr **attr); #endif //IZ1_ATTR_H diff --git a/iz1/include/html_tag/tag.h b/iz1/include/html_tag/tag.h index 73bc1e6..d7e812c 100644 --- a/iz1/include/html_tag/tag.h +++ b/iz1/include/html_tag/tag.h @@ -24,12 +24,15 @@ typedef struct { char *name; bool is_opening; - tag_attr *attributes; + size_t attributes_count; + tag_attr **attributes; } html_tag; html_tag *parse_tag(const char *str); -int parse_status(const char *str, html_tag *tag); +size_t parse_status(const char *str, html_tag *tag); + +void free_tag(html_tag **tag); diff --git a/iz1/include/my_str/mem.h b/iz1/include/my_str/mem.h index 35a1287..5175738 100644 --- a/iz1/include/my_str/mem.h +++ b/iz1/include/my_str/mem.h @@ -13,7 +13,7 @@ size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); size_t str_create_copy(char **to_allocate, const char *to_copy); -size_t str_create_word(char **to_allocate, const char *src, char word_end); +size_t str_create_word(char **to_allocate, const char *src, const char *sep); #endif //IZ1_MEM_H diff --git a/iz1/src/alg.c b/iz1/src/alg.c index a5a0afb..7afcb0c 100644 --- a/iz1/src/alg.c +++ b/iz1/src/alg.c @@ -1,5 +1,7 @@ #include "my_str/alg.h" +#include + int str_find(const char *str, char c) { int i = 0; @@ -11,7 +13,7 @@ int str_find(const char *str, char c) int str_first_char_occurence(const char *str, const char *c) { int i = 0; - while (str_find(c, str[i]) == -1 && str[i] != '\0') + while (c[str_find(c, str[i])] == '\0' && str[i] != '\0') ++i; return i; } diff --git a/iz1/src/attr.c b/iz1/src/attr.c index 5f86aca..6dd928b 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -5,10 +5,12 @@ #include "my_str/mem.h" // Tag attribute create/delete -void free_attr(tag_attr *attr) +void free_attr(tag_attr **attr) { - free(attr->name); - free(attr->value); + free((*attr)->name); + free((*attr)->value); + free(*attr); + *attr = NULL; } tag_attr *parse_attr(const char *str, int *attr_end) @@ -16,14 +18,26 @@ tag_attr *parse_attr(const char *str, int *attr_end) const char *str_start = str; tag_attr *attr = (tag_attr *) malloc(sizeof(tag_attr)); - str += str_create_word(&attr->name, str, '='); + str += str_create_word(&attr->name, str, "="); if (*str == '"') - str += str_create_word(&attr->value, str + 1, '"'); + str += str_create_word(&attr->value, str + 1, "\"") + 2; else - str += str_create_word(&attr->value, str, ' '); + str += str_create_word(&attr->value, str, " >"); ptrdiff_t attr_end_ = str - str_start; - *attr_end -= (int)(attr_end_); + *attr_end = (int) (attr_end_); return attr; -} \ No newline at end of file +} + +tag_attr **parse_attr_arr(const char *str, size_t count) +{ + tag_attr **attr_arr = (tag_attr **) malloc(count * sizeof(tag_attr *)); + for (size_t i = 0; i < count; ++i) + { + int attr_end = 0; + attr_arr[i] = parse_attr(str, &attr_end); + str += attr_end; + } + return attr_arr; +} diff --git a/iz1/src/mem.c b/iz1/src/mem.c index 807d202..a68589e 100644 --- a/iz1/src/mem.c +++ b/iz1/src/mem.c @@ -23,8 +23,8 @@ int n(char **to_allocate, const char *to_copy) return str_create_ncopy(to_allocate, to_copy, len); } -size_t str_create_word(char **to_allocate, const char *src, char sep) +size_t str_create_word(char **to_allocate, const char *src, const char *sep) { - int word_end = str_find(src, sep); + int word_end = str_first_char_occurence(src, sep); return str_create_ncopy(to_allocate, src, word_end); } diff --git a/iz1/src/tag.c b/iz1/src/tag.c index e7aa016..1e5ba61 100644 --- a/iz1/src/tag.c +++ b/iz1/src/tag.c @@ -1,32 +1,46 @@ #include "html_tag/tag.h" #include "my_str/mem.h" +#include "my_str/alg.h" html_tag *parse_tag(const char *str) { - html_tag *tag = (html_tag *)malloc(sizeof(html_tag)); + html_tag *tag = (html_tag *) malloc(sizeof(html_tag)); if (tag == NULL) return NULL; str += parse_status(str, tag); + tag->attributes_count = str_count(str, '='); + + if (!tag->is_opening || tag->attributes_count == 0) + str += str_create_word(&tag->name, str, ">"); + else + str += str_create_word(&tag->name, str, " "); + + tag->attributes = parse_attr_arr(str, tag->attributes_count); + return tag; } -int parse_status(const char *str, html_tag *tag) +size_t parse_status(const char *str, html_tag *tag) { int i = 0; if (str[i] == '<') { ++i; - if (str[i + 1] == '/') + if (str[i] == '/') { tag->is_opening = false; ++i; - } - else + } else tag->is_opening = true; } return i; } +void free_tag(html_tag **tag) +{ + free(*tag); + *tag = NULL; +} From 9852dfe4b77a59dcab926d524891698f366c948f Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 17:47:03 +0300 Subject: [PATCH 20/65] Updated free function --- iz1/include/html_tag/{tag.h => html_tag.h} | 6 +++--- iz1/src/{tag.c => html_tag.c} | 6 +++++- iz1/src/main.c | 2 +- iz1/test/html_tag.cpp | 2 +- 4 files changed, 10 insertions(+), 6 deletions(-) rename iz1/include/html_tag/{tag.h => html_tag.h} (94%) rename iz1/src/{tag.c => html_tag.c} (82%) diff --git a/iz1/include/html_tag/tag.h b/iz1/include/html_tag/html_tag.h similarity index 94% rename from iz1/include/html_tag/tag.h rename to iz1/include/html_tag/html_tag.h index d7e812c..096bf4c 100644 --- a/iz1/include/html_tag/tag.h +++ b/iz1/include/html_tag/html_tag.h @@ -12,8 +12,8 @@ * */ -#ifndef IZ1_TAG_H -#define IZ1_TAG_H +#ifndef IZ1_HTML_TAG_H +#define IZ1_HTML_TAG_H #include #include @@ -36,4 +36,4 @@ void free_tag(html_tag **tag); -#endif //IZ1_TAG_H +#endif //IZ1_HTML_TAG_H diff --git a/iz1/src/tag.c b/iz1/src/html_tag.c similarity index 82% rename from iz1/src/tag.c rename to iz1/src/html_tag.c index 1e5ba61..75c1454 100644 --- a/iz1/src/tag.c +++ b/iz1/src/html_tag.c @@ -1,4 +1,4 @@ -#include "html_tag/tag.h" +#include "html_tag/html_tag.h" #include "my_str/mem.h" #include "my_str/alg.h" @@ -41,6 +41,10 @@ size_t parse_status(const char *str, html_tag *tag) void free_tag(html_tag **tag) { + free((*tag)->name); + for (size_t i = 0; i < (*tag)->attributes_count; ++i) + free_attr((*tag)->attributes + i); + free((*tag)->attributes); free(*tag); *tag = NULL; } diff --git a/iz1/src/main.c b/iz1/src/main.c index 3e1373e..7e7368d 100644 --- a/iz1/src/main.c +++ b/iz1/src/main.c @@ -5,7 +5,7 @@ */ #include -#include "html_tag/tag.h" +#include "html_tag/html_tag.h" #define MAX_STR_LEN 256 diff --git a/iz1/test/html_tag.cpp b/iz1/test/html_tag.cpp index 4eb722c..c71fe47 100644 --- a/iz1/test/html_tag.cpp +++ b/iz1/test/html_tag.cpp @@ -2,7 +2,7 @@ #include extern "C" { -#include "html_tag/tag.h" +#include "html_tag/html_tag.h" } TEST(tag_correct_input, no_quotes) From 52faee6249804674298660d9468686de7dd6929f Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 22:20:23 +0300 Subject: [PATCH 21/65] Updated tests --- .travis.yml | 15 ++++--- iz1/include/html_tag/attr.h | 3 ++ iz1/include/html_tag/html_tag.h | 2 + iz1/include/my_str/alg.h | 2 + iz1/src/attr.c | 27 ++++++++++++- iz1/src/html_tag.c | 34 ++++++++++++++++ iz1/test/CMakeLists.txt | 6 +-- iz1/test/check_attr_format.cpp | 63 ++++++++++++++++++++++++++++++ iz1/test/check_html_tag_format.cpp | 61 +++++++++++++++++++++++++++++ 9 files changed, 203 insertions(+), 10 deletions(-) create mode 100644 iz1/test/check_attr_format.cpp create mode 100644 iz1/test/check_html_tag_format.cpp diff --git a/.travis.yml b/.travis.yml index 3ed4e4f..8abbfbd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,15 @@ -language: c +language: + - c + - cpp sudo: false # only for faster builds + +before_script: + - cd iz1 + - mkdir build + - cd build + script: - - cd iz1 - - mkdir build - - cd build - cmake .. && make - cd test && ctest -after_success: - - bash <(curl -s https://codecov.io/bash) diff --git a/iz1/include/html_tag/attr.h b/iz1/include/html_tag/attr.h index e2c26a2..cdd2478 100644 --- a/iz1/include/html_tag/attr.h +++ b/iz1/include/html_tag/attr.h @@ -6,6 +6,7 @@ #define IZ1_ATTR_H #include +#include typedef struct { @@ -13,6 +14,8 @@ typedef struct char *value; } tag_attr; +bool check_attr_format(const char *str, size_t *attr_end); + tag_attr *parse_attr(const char *str, int *attr_end); tag_attr **parse_attr_arr(const char *str, size_t count); diff --git a/iz1/include/html_tag/html_tag.h b/iz1/include/html_tag/html_tag.h index 096bf4c..db5114c 100644 --- a/iz1/include/html_tag/html_tag.h +++ b/iz1/include/html_tag/html_tag.h @@ -28,6 +28,8 @@ typedef struct tag_attr **attributes; } html_tag; +bool check_html_tag_format(const char *str); + html_tag *parse_tag(const char *str); size_t parse_status(const char *str, html_tag *tag); diff --git a/iz1/include/my_str/alg.h b/iz1/include/my_str/alg.h index 1ea10a8..8f34939 100644 --- a/iz1/include/my_str/alg.h +++ b/iz1/include/my_str/alg.h @@ -5,6 +5,8 @@ #ifndef IZ1_ALG_H #define IZ1_ALG_H +#define ASCII_LETTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + int str_find(const char *str, char c); int str_first_char_occurence(const char *str, const char *c); diff --git a/iz1/src/attr.c b/iz1/src/attr.c index 6dd928b..b6a3b68 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -3,8 +3,33 @@ #include #include "my_str/mem.h" +#include "my_str/alg.h" + +bool check_attr_format(const char *str, size_t *attr_end) +{ + size_t eq_pos = str_find(str, '='); + bool ok = true; + if (str[eq_pos] == '\0') + ok = false; + + for (int i = 0; ok && i < eq_pos; ++i) + if (str[i] == ' ') + ok = false; + + if (ok) + { + eq_pos++; + if (str[eq_pos] == '\"') + *attr_end = str_find(str + eq_pos + 1, '\"') + 2; + else + *attr_end = str_first_char_occurence(str + eq_pos, " >"); + + *attr_end += eq_pos; + ok = (str[*attr_end] != '\0'); + } + return ok; +} -// Tag attribute create/delete void free_attr(tag_attr **attr) { free((*attr)->name); diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c index 75c1454..a35b915 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/html_tag.c @@ -3,6 +3,40 @@ #include "my_str/mem.h" #include "my_str/alg.h" +bool check_html_tag_format(const char *str) +{ + bool ok = str[0] == '<'; + if (ok && str[1] == '/') + { + size_t closing_pos = str_find(str, '>'); + for (size_t i = 2; ok && i < closing_pos; ++i) + ok += (ASCII_LETTERS[str_find(ASCII_LETTERS, str[i])] != '\0'); + } else if (ok) + { + size_t name_end = str_first_char_occurence(str, " >"); + for (size_t i = 1; ok && i < name_end; ++i) + ok += (ASCII_LETTERS[str_find(ASCII_LETTERS, str[i])] != '\0'); + + if (ok) + { + size_t closing_pos = str_find(str, '>'); + ok = (str[closing_pos] == '>'); + } + + if (ok) + { + size_t attr_end = name_end; + str += attr_end; + while (ok && str[0] != '>') + { + ok = check_attr_format(str + 1, &attr_end); + str += attr_end + 1; + } + } + } + return ok; +} + html_tag *parse_tag(const char *str) { html_tag *tag = (html_tag *) malloc(sizeof(html_tag)); diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt index e39e463..0d87600 100644 --- a/iz1/test/CMakeLists.txt +++ b/iz1/test/CMakeLists.txt @@ -6,13 +6,13 @@ list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") -foreach(file ${tests}) +foreach (file ${tests}) set(name) get_filename_component(name ${file} NAME_WE) add_executable("${name}_tests" ${sources} ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp html_tag.cpp) + "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp html_tag.cpp check_attr_format.cpp check_html_tag_format.cpp) target_link_libraries("${name}_tests" gtest_main) add_test(NAME ${name} COMMAND "${name}_tests") -endforeach() \ No newline at end of file +endforeach () \ No newline at end of file diff --git a/iz1/test/check_attr_format.cpp b/iz1/test/check_attr_format.cpp new file mode 100644 index 0000000..b5d2e83 --- /dev/null +++ b/iz1/test/check_attr_format.cpp @@ -0,0 +1,63 @@ +#include "gtest/gtest.h" +#include + +extern "C" { +#include "html_tag/attr.h" +} + +TEST(format_checker_correct, test1) +{ + char str[] = "attr1=value1 "; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + +TEST(format_checker_correct, test2) +{ + char str[] = "attr1=\"value1\" "; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + +TEST(format_checker_correct, test3) +{ + char str[] = "attr1=\"value1 value2\" "; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + + +TEST(format_checker_correct, test1_last) +{ + char str[] = "attr1=value1>"; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + +TEST(format_checker_correct, test2_last) +{ + char str[] = "attr1=\"value1\">"; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + +TEST(format_checker_correct, test3_last) +{ + char str[] = "attr1=\"value1 value2\">"; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), true); +} + +TEST(format_checker_incorrect, random_word) +{ + char str[] = "random_word"; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), false); +} + +TEST(format_checker_incorrect, space_before_eq) +{ + char str[] = "word attr=val"; + size_t attr_end; + ASSERT_EQ(check_attr_format(str, &attr_end), false); +} diff --git a/iz1/test/check_html_tag_format.cpp b/iz1/test/check_html_tag_format.cpp new file mode 100644 index 0000000..ca45bee --- /dev/null +++ b/iz1/test/check_html_tag_format.cpp @@ -0,0 +1,61 @@ +#include "gtest/gtest.h" +#include + +extern "C" { +#include "html_tag/html_tag.h" +} + +TEST(tag_format_check_correct, simple_opening) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, simple_closing) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_one_attr) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_two_attr) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_two_quoted_attr) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_two_quoted_attr_r) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + + +TEST(tag_format_check_correct, opening_two_quoted_attr_) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_three_quoted_attr) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} + +TEST(tag_format_check_correct, opening_three_quoted_attr_) +{ + char str[] = ""; + ASSERT_EQ(check_html_tag_format(str), true); +} From f71c01d7a4a0ad771be8c344d1a0594ad8a837f0 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 13 Oct 2020 22:25:53 +0300 Subject: [PATCH 22/65] updated travis --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 8abbfbd..868a1cb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,8 @@ language: - c - cpp -sudo: false # only for faster builds +os: linux +dist: xenial before_script: - cd iz1 From b3d2cf2a01cb0080d357062e34fb8e8ddd0a70f1 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 11:41:18 +0300 Subject: [PATCH 23/65] updated travis --- .travis.yml | 5 ++-- iz1/include/my_str/alg.h | 2 +- iz1/src/html_tag.c | 7 ++++-- iz1/test/check_html_tag_format.cpp | 38 +++++++++++++++++++++++++++--- 4 files changed, 43 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 868a1cb..b72a983 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,9 @@ +sudo: false + language: - c - cpp -os: linux -dist: xenial - before_script: - cd iz1 - mkdir build diff --git a/iz1/include/my_str/alg.h b/iz1/include/my_str/alg.h index 8f34939..89c863b 100644 --- a/iz1/include/my_str/alg.h +++ b/iz1/include/my_str/alg.h @@ -5,7 +5,7 @@ #ifndef IZ1_ALG_H #define IZ1_ALG_H -#define ASCII_LETTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +#define ASCII_NAME_ALLOWED "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789\"-" int str_find(const char *str, char c); diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c index a35b915..169e2c7 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/html_tag.c @@ -10,12 +10,12 @@ bool check_html_tag_format(const char *str) { size_t closing_pos = str_find(str, '>'); for (size_t i = 2; ok && i < closing_pos; ++i) - ok += (ASCII_LETTERS[str_find(ASCII_LETTERS, str[i])] != '\0'); + ok = (ASCII_NAME_ALLOWED[str_find(ASCII_NAME_ALLOWED, str[i])] != '\0'); } else if (ok) { size_t name_end = str_first_char_occurence(str, " >"); for (size_t i = 1; ok && i < name_end; ++i) - ok += (ASCII_LETTERS[str_find(ASCII_LETTERS, str[i])] != '\0'); + ok = (ASCII_NAME_ALLOWED[str_find(ASCII_NAME_ALLOWED, str[i])] != '\0'); if (ok) { @@ -39,6 +39,9 @@ bool check_html_tag_format(const char *str) html_tag *parse_tag(const char *str) { + if (!check_html_tag_format(str)) + return NULL; + html_tag *tag = (html_tag *) malloc(sizeof(html_tag)); if (tag == NULL) diff --git a/iz1/test/check_html_tag_format.cpp b/iz1/test/check_html_tag_format.cpp index ca45bee..a505351 100644 --- a/iz1/test/check_html_tag_format.cpp +++ b/iz1/test/check_html_tag_format.cpp @@ -44,18 +44,50 @@ TEST(tag_format_check_correct, opening_two_quoted_attr_r) TEST(tag_format_check_correct, opening_two_quoted_attr_) { - char str[] = ""; + char str[] = R"()"; ASSERT_EQ(check_html_tag_format(str), true); } TEST(tag_format_check_correct, opening_three_quoted_attr) { - char str[] = ""; + char str[] = R"()"; ASSERT_EQ(check_html_tag_format(str), true); } TEST(tag_format_check_correct, opening_three_quoted_attr_) { - char str[] = ""; + char str[] = R"()"; ASSERT_EQ(check_html_tag_format(str), true); } + +TEST(tag_format_check_incorrect, no_name) +{ + char str[] = R"()"; + ASSERT_EQ(check_html_tag_format(str), false); +} + +TEST(tag_format_check_incorrect, closing_tag_attrs) +{ + char str[] = R"()"; + ASSERT_EQ(check_html_tag_format(str), false); +} + +TEST(tag_format_check_incorrect, random_symbols) +{ + char str[] = R"(lskdjfo isdfo)"; + ASSERT_EQ(check_html_tag_format(str), false); +} + +TEST(tag_format_check_incorrect, random_things_inside_tag) +{ + char str[] = R"()"; + ASSERT_EQ(check_html_tag_format(str), false); +} + + + + + + + + From 1154cdfe6b9eddf8b68d665a07d4eb447a7d63f0 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 11:42:22 +0300 Subject: [PATCH 24/65] updated travis --- .travis.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index b72a983..febef36 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,9 @@ sudo: false +dist: xenial + +os: linux + language: - c - cpp @@ -10,6 +14,6 @@ before_script: - cd build script: - - cmake .. && make - - cd test && ctest + - cmake .. && make + - cd test && ctest From 5cc797f79fd30470bea000ac6d2a3500c2951f4c Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 11:48:19 +0300 Subject: [PATCH 25/65] updated travis --- .travis.yml | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/.travis.yml b/.travis.yml index febef36..7451b5f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,19 +1,28 @@ -sudo: false +# sudo: false -dist: xenial +# dist: xenial -os: linux +# os: linux -language: - - c - - cpp +# language: +# - c +# - cpp -before_script: - - cd iz1 - - mkdir build - - cd build +# before_script: +# - cd iz1 +# - mkdir build +# - cd build -script: - - cmake .. && make - - cd test && ctest +# script: + # - cmake .. && make + # - cd test && ctest + +language: c +sudo: false # only for faster builds +script: + - cd iz1 + - mkdir build + - cd build + - cmake .. && make + - cd test && ctest From 95809d1f6f894d7c96e83010445ad21d762bb532 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 11:55:37 +0300 Subject: [PATCH 26/65] reverted travis --- .travis.yml | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7451b5f..3ed4e4f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,28 +1,12 @@ -# sudo: false - -# dist: xenial - -# os: linux - -# language: -# - c -# - cpp - -# before_script: -# - cd iz1 -# - mkdir build -# - cd build - -# script: - # - cmake .. && make - # - cd test && ctest - language: c sudo: false # only for faster builds script: - cd iz1 - - mkdir build + - mkdir build - cd build - cmake .. && make - cd test && ctest + +after_success: + - bash <(curl -s https://codecov.io/bash) From 49f8e6271cd5a1f88b58346779d5a8b7f52281e3 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 14:40:55 +0300 Subject: [PATCH 27/65] Updated memcheck tests --- iz1/CMakeLists.txt | 21 ++++++++++++++++----- iz1/mybuild.sh | 6 ++++++ iz1/test/CMakeLists.txt | 3 ++- 3 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 iz1/mybuild.sh diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 42c4756..bc3eb7d 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -2,19 +2,30 @@ cmake_minimum_required(VERSION 3.1) project(iz1 C CXX) -set (CMAKE_C_STANDARD 99) -set (CMAKE_CXX_STANDARD 17) +set(CMAKE_C_STANDARD 99) +set(CMAKE_CXX_STANDARD 17) + +## +### Valgrind +## + +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") + ## ### Test definitions ### ## +include (CTest) configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) execute_process(COMMAND ${CMAKE_COMMAND} --build . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src ${CMAKE_BINARY_DIR}/googletest-build) @@ -33,4 +44,4 @@ file(GLOB sources "${PROJECT_SOURCE_DIR}/include/my_str/*.h" "${PROJECT_SOURCE_DIR}/src/*.c") -add_executable(iz1 ${sources} ) +add_executable(iz1 ${sources}) diff --git a/iz1/mybuild.sh b/iz1/mybuild.sh new file mode 100644 index 0000000..3a91d01 --- /dev/null +++ b/iz1/mybuild.sh @@ -0,0 +1,6 @@ +rm -rf build; +mkdir build; +cd build; +cmake ..; +make; + diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt index 0d87600..735a15b 100644 --- a/iz1/test/CMakeLists.txt +++ b/iz1/test/CMakeLists.txt @@ -1,5 +1,6 @@ include_directories("${PROJECT_SOURCE_DIR}/include") + file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") @@ -12,7 +13,7 @@ foreach (file ${tests}) add_executable("${name}_tests" ${sources} ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp" attr.cpp html_tag.cpp check_attr_format.cpp check_html_tag_format.cpp) + "${PROJECT_SOURCE_DIR}/test/main.cpp") target_link_libraries("${name}_tests" gtest_main) add_test(NAME ${name} COMMAND "${name}_tests") endforeach () \ No newline at end of file From e58bc21ee04fb5973d9ddfe17c99f40391f7576a Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 15:41:03 +0300 Subject: [PATCH 28/65] Updated travis for memcheck --- .travis.yml | 40 +++++++++++++++++++++++++++++++--------- iz1/CMakeLists.txt | 1 + 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3ed4e4f..a55a38a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,34 @@ -language: c +language: cpp +os: linux +compiler: gcc -sudo: false # only for faster builds -script: - - cd iz1 - - mkdir build +env: + - DIR=iz1 + + +sudo: false + +before_scrip: + - mkdir build - cd build - - cmake .. && make - - cd test && ctest -after_success: - - bash <(curl -s https://codecov.io/bash) +matrix: + # + # Valgrind + # + - os: linux + env: + - TEST="Valgrind" + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-6 + - g++-6 + - valgrind + script: + - cmake .. + - make + - ctest -T memcheck + diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index bc3eb7d..0955433 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -18,6 +18,7 @@ set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode ## ### Test definitions ### ## + include (CTest) configure_file(CMakeLists.txt.in From 0a64c1637d7822f0b864be6a776fbeeb2431338d Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 15:45:12 +0300 Subject: [PATCH 29/65] Updated travis --- .travis.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index a55a38a..3624830 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,11 +21,7 @@ matrix: - TEST="Valgrind" addons: apt: - sources: - - ubuntu-toolchain-r-test packages: - - gcc-6 - - g++-6 - valgrind script: - cmake .. From a055d853733a493dc323f4c87f6bdba2ef871527 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 15:55:15 +0300 Subject: [PATCH 30/65] updated travis --- .travis.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3624830..652d15a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,13 +2,10 @@ language: cpp os: linux compiler: gcc -env: - - DIR=iz1 - - sudo: false before_scrip: + - cd iz1 - mkdir build - cd build From 2438f8f45e6378191b249778aa4380d0472a021b Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:17:59 +0300 Subject: [PATCH 31/65] Added main app code --- iz1/src/main.c | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/iz1/src/main.c b/iz1/src/main.c index 7e7368d..96ceb78 100644 --- a/iz1/src/main.c +++ b/iz1/src/main.c @@ -11,10 +11,25 @@ int main() { - char line[MAX_STR_LEN] = "o>"; -// fgets(line, MAX_STR_LEN, stdin); - html_tag *tag = parse_tag(line); - printf("line = '%s'\n", line); - printf("Tag:\nname: \t\t'%s'\nis_opening: \t'%d'\n", tag->name, tag->is_opening); + char str[MAX_STR_LEN]; + fgets(str, sizeof(str), stdin); + html_tag *tag = parse_tag(str); + if (!tag) + puts("Wrong tag format!"); + else + { + printf("Tag name = \"%s\"\n", tag->name); + if (tag->is_opening) + puts("Opening tag"); + else + puts("Closing tag"); + if (tag->attributes_count) + { + puts("Attributes:"); + for (size_t i = 0; i < tag->attributes_count; ++i) + printf("%s=\"%s\"\n", tag->attributes[i]->name, tag->attributes[i]->value); + } + free_tag(&tag); + } return 0; -} +} \ No newline at end of file From 0f03d45dd48f3b5687792c7129498b96248c9dcb Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:23:00 +0300 Subject: [PATCH 32/65] Added cppcheck --- .travis.yml | 14 ++++++++++++ iz1/CMakeLists.txt | 50 ++++++++++++++++++++++++++++++++++++++++++- iz1/CMakeLists.txt.in | 8 ++++--- 3 files changed, 68 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 652d15a..799691a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,3 +25,17 @@ matrix: - make - ctest -T memcheck + # + # CppCheck + # + - os: linux + env: + - TEST="CppCheck" + addons: + apt: + sources: + - ubuntu-toolchain-r-test + script: + - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. + - make + - make check diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 0955433..12e2481 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -4,6 +4,8 @@ project(iz1 C CXX) set(CMAKE_C_STANDARD 99) set(CMAKE_CXX_STANDARD 17) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + ## ### Valgrind @@ -19,7 +21,7 @@ set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode ### Test definitions ### ## -include (CTest) +include(CTest) configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) @@ -34,10 +36,56 @@ add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src enable_testing() add_subdirectory(test) + +## +### Cppecheck +## + +if (ENABLE_CPPCHECK) + + list(APPEND CPPCHECK_CMAKE_ARGS + "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}" + ) + include(ExternalProject) + ExternalProject_Add( + cppcheck + GIT_REPOSITORY https://github.com/danmar/cppcheck.git + GIT_TAG 1.79 + GIT_SHALLOW 1 + CMAKE_ARGS ${CPPCHECK_CMAKE_ARGS} + PREFIX ${CMAKE_BINARY_DIR}/external/cppcheck/prefix + TMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/tmp + STAMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/stamp + DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/download + SOURCE_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/src + BINARY_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/build + ) + + list(APPEND CPPCHECK_ARGS + --enable=warning,style,performance,portability,unusedFunction + --std=c99 + --verbose + --error-exitcode=1 + --language=c + -DMAIN=main + -I ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include/*.h + ${CMAKE_SOURCE_DIR}/src/*.c + ) + + add_custom_target( + check + COMMAND ${CMAKE_BINARY_DIR}/bin/cppcheck ${CPPCHECK_ARGS} + COMMENT "running cppcheck" + ) + +endif () + ## ### Source definitions ### ## + include_directories("${PROJECT_SOURCE_DIR}/include") file(GLOB sources diff --git a/iz1/CMakeLists.txt.in b/iz1/CMakeLists.txt.in index 586d9d6..7499d73 100644 --- a/iz1/CMakeLists.txt.in +++ b/iz1/CMakeLists.txt.in @@ -1,9 +1,11 @@ cmake_minimum_required(VERSION 3.1) -project(googletest-download NONE) +project(extern-download NONE) + include(ExternalProject) -ExternalProject_Add(googletest +ExternalProject_Add( +googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.8.1 SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" @@ -12,4 +14,4 @@ ExternalProject_Add(googletest BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" -) \ No newline at end of file +) From bee60d6ed832d1480bb39195ec0f966d5c0061c1 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:24:47 +0300 Subject: [PATCH 33/65] updated travis --- .travis.yml | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index 799691a..d7648b0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,12 +30,8 @@ matrix: # - os: linux env: - - TEST="CppCheck" - addons: - apt: - sources: - - ubuntu-toolchain-r-test - script: - - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. - - make - - make check + - TEST="CppCheck" + script: + - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. + - make + - make check From efc3cf233b67d7cc1a0690d19960221b164c910d Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:26:17 +0300 Subject: [PATCH 34/65] updated travis --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index d7648b0..aa3c11e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,15 @@ language: cpp os: linux +dist: xenial compiler: gcc -sudo: false -before_scrip: +before_script: - cd iz1 - mkdir build - cd build -matrix: +jobs: # # Valgrind # From 3ad95c031876a6a109105a37218b9cebf6860b76 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:28:22 +0300 Subject: [PATCH 35/65] correct cppcheck for travis --- .travis.yml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index aa3c11e..d4cfd80 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,11 +27,12 @@ jobs: # # CppCheck - # - - os: linux - env: - - TEST="CppCheck" - script: - - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. - - make - - make check + # + - os: linux + env: + - TEST="CppCheck" + + script: + - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. + - make + - make checkk From a97c2e6df6d90282c4dc81512f66f4d23edb0d32 Mon Sep 17 00:00:00 2001 From: Paul Date: Wed, 14 Oct 2020 17:40:58 +0300 Subject: [PATCH 36/65] updated travis for cppcheck --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d4cfd80..037ff5c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -35,4 +35,4 @@ jobs: script: - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. - make - - make checkk + - make check From 908a5f818fa3c20cc78652b3abb2347a7f442007 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 09:07:12 +0300 Subject: [PATCH 37/65] updated travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 037ff5c..fd63411 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,6 +33,6 @@ jobs: - TEST="CppCheck" script: - - cmake -DENABLE_CPPCHECK=ON -DCMAKE_CXX_COMPILER="g++-6" .. + - cmake -DENABLE_CPPCHECK=ON .. - make - make check From e63c6a21b7eee86bdf0d426146e3e5bdc2dd23bd Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 09:18:18 +0300 Subject: [PATCH 38/65] Updated CmakeLIsts for gcov --- iz1/CMakeLists.txt | 8 ++++++++ iz1/mybuild.sh | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt index 12e2481..4cb7fee 100644 --- a/iz1/CMakeLists.txt +++ b/iz1/CMakeLists.txt @@ -6,6 +6,14 @@ set(CMAKE_C_STANDARD 99) set(CMAKE_CXX_STANDARD 17) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +# +### GCOV +# + +if (ENABLE_GCOV) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") +endif () + ## ### Valgrind diff --git a/iz1/mybuild.sh b/iz1/mybuild.sh index 3a91d01..9d51fc8 100644 --- a/iz1/mybuild.sh +++ b/iz1/mybuild.sh @@ -1,6 +1,6 @@ rm -rf build; mkdir build; cd build; -cmake ..; +cmake -DENABLE_GCOV=ON ..; make; From 9f0afab903f82a58f54dbdb02cea9b06750e5b93 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 10:24:50 +0300 Subject: [PATCH 39/65] added gcovr to tests --- .travis.yml | 14 ++++++++++++++ iz1/mybuild.sh | 4 ++++ iz1/test/CMakeLists.txt | 6 +++++- 3 files changed, 23 insertions(+), 1 deletion(-) mode change 100644 => 100755 iz1/mybuild.sh diff --git a/.travis.yml b/.travis.yml index fd63411..329a732 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,3 +36,17 @@ jobs: - cmake -DENABLE_CPPCHECK=ON .. - make - make check + + # + # Coverage + # + - os: linux + env: + - TEST="GCovr" + + script: + - cmake -DENABLE_GCOV + - make + - ctest + - cd .. && gcovr + diff --git a/iz1/mybuild.sh b/iz1/mybuild.sh old mode 100644 new mode 100755 index 9d51fc8..6cea912 --- a/iz1/mybuild.sh +++ b/iz1/mybuild.sh @@ -1,6 +1,10 @@ +#! /bin/bash + rm -rf build; mkdir build; cd build; cmake -DENABLE_GCOV=ON ..; make; +gcovr --html-details > cov_res.html; + diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt index 735a15b..50c75f3 100644 --- a/iz1/test/CMakeLists.txt +++ b/iz1/test/CMakeLists.txt @@ -1,12 +1,16 @@ include_directories("${PROJECT_SOURCE_DIR}/include") - file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") +if (ENABLE_GCOV) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") +endif () + + foreach (file ${tests}) set(name) get_filename_component(name ${file} NAME_WE) From c5ed0550f0de201935c8dd8c3d1adadeb624c9a5 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 10:30:11 +0300 Subject: [PATCH 40/65] updated travis for gcovr --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 329a732..e3ed24e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,7 +43,9 @@ jobs: - os: linux env: - TEST="GCovr" - + before_script: + - sudo apt-get install gcov + - pip3 install gcovr script: - cmake -DENABLE_GCOV - make From be08dddce3fe767c3beb77bb904ba946580f63fc Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 10:33:01 +0300 Subject: [PATCH 41/65] updated travis for gcovr --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index e3ed24e..868af12 100644 --- a/.travis.yml +++ b/.travis.yml @@ -44,6 +44,7 @@ jobs: env: - TEST="GCovr" before_script: + - sudo apt-get update - sudo apt-get install gcov - pip3 install gcovr script: From 964d0b168166f6d6be68d01fed15fb43d4862a91 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 10:36:39 +0300 Subject: [PATCH 42/65] updated travis for gcov --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 868af12..1cb53fe 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,9 +43,11 @@ jobs: - os: linux env: - TEST="GCovr" + addons: + apt: + packages: + - gcov before_script: - - sudo apt-get update - - sudo apt-get install gcov - pip3 install gcovr script: - cmake -DENABLE_GCOV From f8c099ba47c7e518482b5d484d9448a73511c0d2 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 10:39:38 +0300 Subject: [PATCH 43/65] updated travis for gcov --- .travis.yml | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1cb53fe..960be4d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,18 +40,18 @@ jobs: # # Coverage # - - os: linux - env: - - TEST="GCovr" - addons: - apt: - packages: - - gcov - before_script: - - pip3 install gcovr - script: - - cmake -DENABLE_GCOV - - make - - ctest - - cd .. && gcovr + # - os: linux + # env: + # - TEST="GCovr" + # addons: + # apt: + # packages: + # - gcov + # before_script: + # - pip3 install gcovr + # script: + # - cmake -DENABLE_GCOV + # - make + # - ctest + # - cd .. && gcovr From 839dfbeb21ae705d61c5f6a603a9e2e960a60f3e Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:45:54 +0300 Subject: [PATCH 44/65] Solved pull request problems --- iz1/include/html_tag/attr.h | 15 +++++++-------- iz1/include/html_tag/html_tag.h | 4 +--- iz1/include/my_str/alg.h | 4 ---- iz1/include/my_str/mem.h | 5 ----- iz1/src/alg.c | 2 -- iz1/src/attr.c | 10 +++++----- iz1/test/attr.cpp | 6 +++--- 7 files changed, 16 insertions(+), 30 deletions(-) diff --git a/iz1/include/html_tag/attr.h b/iz1/include/html_tag/attr.h index cdd2478..d4ecce5 100644 --- a/iz1/include/html_tag/attr.h +++ b/iz1/include/html_tag/attr.h @@ -1,7 +1,3 @@ -// -// Created by Pavel Cheklin on 11/10/2020. -// - #ifndef IZ1_ATTR_H #define IZ1_ATTR_H @@ -12,14 +8,17 @@ typedef struct { char *name; char *value; -} tag_attr; +} tag_attr_t; +// Функция проверки аттрибута тега (тег располагается в начале строкии и +// заканчивается либо символом '>', либо пробелом. Конец аттрибута записывается +// в переменную attr_end bool check_attr_format(const char *str, size_t *attr_end); -tag_attr *parse_attr(const char *str, int *attr_end); +tag_attr_t *parse_attr(const char *str, int *attr_end); -tag_attr **parse_attr_arr(const char *str, size_t count); +tag_attr_t **parse_attr_arr(const char *str, size_t count); -void free_attr(tag_attr **attr); +void free_attr(tag_attr_t **attr); #endif //IZ1_ATTR_H diff --git a/iz1/include/html_tag/html_tag.h b/iz1/include/html_tag/html_tag.h index db5114c..439552e 100644 --- a/iz1/include/html_tag/html_tag.h +++ b/iz1/include/html_tag/html_tag.h @@ -25,7 +25,7 @@ typedef struct char *name; bool is_opening; size_t attributes_count; - tag_attr **attributes; + tag_attr_t **attributes; } html_tag; bool check_html_tag_format(const char *str); @@ -36,6 +36,4 @@ size_t parse_status(const char *str, html_tag *tag); void free_tag(html_tag **tag); - - #endif //IZ1_HTML_TAG_H diff --git a/iz1/include/my_str/alg.h b/iz1/include/my_str/alg.h index 89c863b..0ce08e4 100644 --- a/iz1/include/my_str/alg.h +++ b/iz1/include/my_str/alg.h @@ -1,7 +1,3 @@ -// -// Created by Pavel Cheklin on 11/10/2020. -// - #ifndef IZ1_ALG_H #define IZ1_ALG_H diff --git a/iz1/include/my_str/mem.h b/iz1/include/my_str/mem.h index 5175738..bde03a7 100644 --- a/iz1/include/my_str/mem.h +++ b/iz1/include/my_str/mem.h @@ -1,7 +1,3 @@ -// -// Created by Pavel Cheklin on 10/10/2020. -// - #ifndef IZ1_MEM_H #define IZ1_MEM_H @@ -15,5 +11,4 @@ size_t str_create_copy(char **to_allocate, const char *to_copy); size_t str_create_word(char **to_allocate, const char *src, const char *sep); - #endif //IZ1_MEM_H diff --git a/iz1/src/alg.c b/iz1/src/alg.c index 7afcb0c..bebd3b7 100644 --- a/iz1/src/alg.c +++ b/iz1/src/alg.c @@ -1,7 +1,5 @@ #include "my_str/alg.h" -#include - int str_find(const char *str, char c) { int i = 0; diff --git a/iz1/src/attr.c b/iz1/src/attr.c index b6a3b68..1ba4072 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -30,7 +30,7 @@ bool check_attr_format(const char *str, size_t *attr_end) return ok; } -void free_attr(tag_attr **attr) +void free_attr(tag_attr_t **attr) { free((*attr)->name); free((*attr)->value); @@ -38,10 +38,10 @@ void free_attr(tag_attr **attr) *attr = NULL; } -tag_attr *parse_attr(const char *str, int *attr_end) +tag_attr_t *parse_attr(const char *str, int *attr_end) { const char *str_start = str; - tag_attr *attr = (tag_attr *) malloc(sizeof(tag_attr)); + tag_attr_t *attr = (tag_attr_t *) malloc(sizeof(tag_attr_t)); str += str_create_word(&attr->name, str, "="); if (*str == '"') @@ -55,9 +55,9 @@ tag_attr *parse_attr(const char *str, int *attr_end) return attr; } -tag_attr **parse_attr_arr(const char *str, size_t count) +tag_attr_t **parse_attr_arr(const char *str, size_t count) { - tag_attr **attr_arr = (tag_attr **) malloc(count * sizeof(tag_attr *)); + tag_attr_t **attr_arr = (tag_attr_t **) malloc(count * sizeof(tag_attr_t *)); for (size_t i = 0; i < count; ++i) { int attr_end = 0; diff --git a/iz1/test/attr.cpp b/iz1/test/attr.cpp index 24a2402..d3d0a4f 100644 --- a/iz1/test/attr.cpp +++ b/iz1/test/attr.cpp @@ -11,7 +11,7 @@ TEST(correct_input, no_quotes) char correct_value[] = "value1"; char line[] = "attr1=value1"; int attr_end = 0; - tag_attr *attr = parse_attr(line, &attr_end); + tag_attr_t *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); free_attr(&attr); @@ -23,7 +23,7 @@ TEST(correct_input, quotes_one) char correct_value[] = "value1"; char line[] = "attr1=\"value1\""; int attr_end = 0; - tag_attr *attr = parse_attr(line, &attr_end); + tag_attr_t *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); free_attr(&attr); @@ -35,7 +35,7 @@ TEST(correct_input, quotes_two) char correct_value[] = "value1 value2"; char line[] = "attr1=\"value1 value2\""; int attr_end = 0; - tag_attr *attr = parse_attr(line, &attr_end); + tag_attr_t *attr = parse_attr(line, &attr_end); ASSERT_EQ(strcmp(attr->name, correct_name), 0); ASSERT_EQ(strcmp(attr->value, correct_value), 0); free_attr(&attr); From 141de927be72e0f31a93fbd539acbcb43e303c42 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:50:20 +0300 Subject: [PATCH 45/65] removed commented code --- iz1/mybuild.sh | 10 ---------- iz1/src/alg.c | 2 +- 2 files changed, 1 insertion(+), 11 deletions(-) delete mode 100755 iz1/mybuild.sh diff --git a/iz1/mybuild.sh b/iz1/mybuild.sh deleted file mode 100755 index 6cea912..0000000 --- a/iz1/mybuild.sh +++ /dev/null @@ -1,10 +0,0 @@ -#! /bin/bash - -rm -rf build; -mkdir build; -cd build; -cmake -DENABLE_GCOV=ON ..; -make; -gcovr --html-details > cov_res.html; - - diff --git a/iz1/src/alg.c b/iz1/src/alg.c index bebd3b7..b800474 100644 --- a/iz1/src/alg.c +++ b/iz1/src/alg.c @@ -5,7 +5,7 @@ int str_find(const char *str, char c) int i = 0; while (str[i] != c && str[i] != '\0') ++i; - return i; // str[i] == c ? i : -1; + return i; } int str_first_char_occurence(const char *str, const char *c) From 1e80a5c8e6e84b34e4faf2220bad711427f831b0 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:51:19 +0300 Subject: [PATCH 46/65] added nullptr check --- iz1/src/alg.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/iz1/src/alg.c b/iz1/src/alg.c index b800474..25ae24a 100644 --- a/iz1/src/alg.c +++ b/iz1/src/alg.c @@ -2,6 +2,9 @@ int str_find(const char *str, char c) { + if (!str) + return -1; + int i = 0; while (str[i] != c && str[i] != '\0') ++i; From c54493a3df2bfff03c9c7bb5222beaf054546288 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:52:21 +0300 Subject: [PATCH 47/65] added parentheses --- iz1/src/attr.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/iz1/src/attr.c b/iz1/src/attr.c index 1ba4072..50502bf 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -14,7 +14,9 @@ bool check_attr_format(const char *str, size_t *attr_end) for (int i = 0; ok && i < eq_pos; ++i) if (str[i] == ' ') + { ok = false; + } if (ok) { From f053596a16a66e4693709763155a5d6ba4edf73c Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:55:46 +0300 Subject: [PATCH 48/65] corrected funcion exit --- iz1/src/attr.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/iz1/src/attr.c b/iz1/src/attr.c index 50502bf..b73a864 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -10,25 +10,23 @@ bool check_attr_format(const char *str, size_t *attr_end) size_t eq_pos = str_find(str, '='); bool ok = true; if (str[eq_pos] == '\0') - ok = false; + return false; for (int i = 0; ok && i < eq_pos; ++i) if (str[i] == ' ') { - ok = false; + return false; } - if (ok) - { - eq_pos++; - if (str[eq_pos] == '\"') - *attr_end = str_find(str + eq_pos + 1, '\"') + 2; - else - *attr_end = str_first_char_occurence(str + eq_pos, " >"); + eq_pos++; + if (str[eq_pos] == '\"') + *attr_end = str_find(str + eq_pos + 1, '\"') + 2; + else + *attr_end = str_first_char_occurence(str + eq_pos, " >"); + + *attr_end += eq_pos; + ok = (str[*attr_end] != '\0'); - *attr_end += eq_pos; - ok = (str[*attr_end] != '\0'); - } return ok; } From 0d4bc0d6db87b3a3d83c804657765b149d6ee344 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 14:58:22 +0300 Subject: [PATCH 49/65] check_attr_format refactor --- iz1/src/attr.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/iz1/src/attr.c b/iz1/src/attr.c index b73a864..ad93093 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -8,11 +8,10 @@ bool check_attr_format(const char *str, size_t *attr_end) { size_t eq_pos = str_find(str, '='); - bool ok = true; if (str[eq_pos] == '\0') return false; - for (int i = 0; ok && i < eq_pos; ++i) + for (int i = 0; i < eq_pos; ++i) if (str[i] == ' ') { return false; @@ -25,9 +24,7 @@ bool check_attr_format(const char *str, size_t *attr_end) *attr_end = str_first_char_occurence(str + eq_pos, " >"); *attr_end += eq_pos; - ok = (str[*attr_end] != '\0'); - - return ok; + return str[*attr_end] != '\0'; } void free_attr(tag_attr_t **attr) From 6bcff0174dcb56f83dbaed0e046f6d616de90a0a Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 16:19:48 +0300 Subject: [PATCH 50/65] solved pr problems --- iz1/src/attr.c | 7 +++++-- iz1/src/html_tag.c | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/iz1/src/attr.c b/iz1/src/attr.c index ad93093..c2a9cf9 100644 --- a/iz1/src/attr.c +++ b/iz1/src/attr.c @@ -7,15 +7,18 @@ bool check_attr_format(const char *str, size_t *attr_end) { + if (!str || !attr_end) + return false; + size_t eq_pos = str_find(str, '='); if (str[eq_pos] == '\0') return false; for (int i = 0; i < eq_pos; ++i) + { if (str[i] == ' ') - { return false; - } + } eq_pos++; if (str[eq_pos] == '\"') diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c index 169e2c7..bf4ba45 100644 --- a/iz1/src/html_tag.c +++ b/iz1/src/html_tag.c @@ -5,7 +5,7 @@ bool check_html_tag_format(const char *str) { - bool ok = str[0] == '<'; + bool ok = str && str[0] == '<'; if (ok && str[1] == '/') { size_t closing_pos = str_find(str, '>'); From 427f216f734ae0913044e47ad8068690d4812821 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 15 Oct 2020 16:23:22 +0300 Subject: [PATCH 51/65] added nullptr checks --- iz1/include/my_str/mem.h | 2 -- iz1/src/alg.c | 6 ++++++ iz1/src/mem.c | 12 ++++++------ 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/iz1/include/my_str/mem.h b/iz1/include/my_str/mem.h index bde03a7..216f72f 100644 --- a/iz1/include/my_str/mem.h +++ b/iz1/include/my_str/mem.h @@ -7,8 +7,6 @@ size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); -size_t str_create_copy(char **to_allocate, const char *to_copy); - size_t str_create_word(char **to_allocate, const char *src, const char *sep); #endif //IZ1_MEM_H diff --git a/iz1/src/alg.c b/iz1/src/alg.c index 25ae24a..2b2cedd 100644 --- a/iz1/src/alg.c +++ b/iz1/src/alg.c @@ -13,6 +13,9 @@ int str_find(const char *str, char c) int str_first_char_occurence(const char *str, const char *c) { + if (!str) + return -1; + int i = 0; while (c[str_find(c, str[i])] == '\0' && str[i] != '\0') ++i; @@ -21,6 +24,9 @@ int str_first_char_occurence(const char *str, const char *c) int str_count(const char *str, char c) { + if (!str) + return -1; + int count = 0; while (*str != '\0') count += (*(str++) == c); diff --git a/iz1/src/mem.c b/iz1/src/mem.c index a68589e..c90fa97 100644 --- a/iz1/src/mem.c +++ b/iz1/src/mem.c @@ -5,6 +5,9 @@ size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) { + if (!to_copy || !to_allocate) + return 0; + size_t to_copy_len = strlen(to_copy); size_t allocate_size = (to_copy_len > n ? n : to_copy_len) + 1; *to_allocate = (char *) malloc(allocate_size); @@ -17,14 +20,11 @@ size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) return allocate_size; } -int n(char **to_allocate, const char *to_copy) -{ - size_t len = strlen(to_copy); - return str_create_ncopy(to_allocate, to_copy, len); -} - size_t str_create_word(char **to_allocate, const char *src, const char *sep) { + if (!src || !to_allocate) + return 0; + int word_end = str_first_char_occurence(src, sep); return str_create_ncopy(to_allocate, src, word_end); } From 11df4ae8f1a7fd0536948fbeb6a630b8ea547dc4 Mon Sep 17 00:00:00 2001 From: Paul Date: Fri, 23 Oct 2020 19:52:01 +0300 Subject: [PATCH 52/65] Added iz2 readme --- iz2/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 iz2/README.md diff --git a/iz2/README.md b/iz2/README.md new file mode 100644 index 0000000..a35252e --- /dev/null +++ b/iz2/README.md @@ -0,0 +1,2 @@ +Вариант #23 +Сравните и выведите в консоль время работы последовательного и параллельного с использованием нескольких процессов алгоритмов, каждый из которых выделяет в динамической памяти символьный массив размером 100 Мб и, рассматривая его содержимое как абстрактную переписку, определяет эмоциональную окраску последней. Переписка считается оптимистичной, если диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. From 2acf4bac82cf2a09143758a93dbf2f694f110ff0 Mon Sep 17 00:00:00 2001 From: Paul Date: Fri, 23 Oct 2020 20:01:59 +0300 Subject: [PATCH 53/65] removed old things --- iz2/README.md | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 iz2/README.md diff --git a/iz2/README.md b/iz2/README.md deleted file mode 100644 index a35252e..0000000 --- a/iz2/README.md +++ /dev/null @@ -1,2 +0,0 @@ -Вариант #23 -Сравните и выведите в консоль время работы последовательного и параллельного с использованием нескольких процессов алгоритмов, каждый из которых выделяет в динамической памяти символьный массив размером 100 Мб и, рассматривая его содержимое как абстрактную переписку, определяет эмоциональную окраску последней. Переписка считается оптимистичной, если диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. From 3f5293bdcd4ae7272711f7750d04ca88bdaa2fa0 Mon Sep 17 00:00:00 2001 From: Paul Date: Fri, 23 Oct 2020 20:10:52 +0300 Subject: [PATCH 54/65] Added initial project version --- iz2/CMakeLists.txt | 103 ++++++++++++++++++++++++++++++++++++++++ iz2/CMakeLists.txt.in | 17 +++++++ iz2/README.MD | 20 ++++++++ iz2/include/header.h | 3 ++ iz2/src/main.c | 12 +++++ iz2/src/source.c | 6 +++ iz2/test/CMakeLists.txt | 23 +++++++++ iz2/test/f.cpp | 10 ++++ iz2/test/main.cpp | 6 +++ 9 files changed, 200 insertions(+) create mode 100644 iz2/CMakeLists.txt create mode 100644 iz2/CMakeLists.txt.in create mode 100644 iz2/README.MD create mode 100644 iz2/include/header.h create mode 100644 iz2/src/main.c create mode 100644 iz2/src/source.c create mode 100644 iz2/test/CMakeLists.txt create mode 100644 iz2/test/f.cpp create mode 100644 iz2/test/main.cpp diff --git a/iz2/CMakeLists.txt b/iz2/CMakeLists.txt new file mode 100644 index 0000000..300d1c9 --- /dev/null +++ b/iz2/CMakeLists.txt @@ -0,0 +1,103 @@ +cmake_minimum_required(VERSION 3.1) + +project(iz2 C CXX) + +set(CMAKE_C_STANDARD 99) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# +### GCOV +# + +if (ENABLE_GCOV) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") +endif () + + +## +### Valgrind +## + +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") + + +## +### Test definitions ### +## + +include(CTest) + +configure_file(CMakeLists.txt.in + googletest-download/CMakeLists.txt) +execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) +execute_process(COMMAND ${CMAKE_COMMAND} --build . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) + +add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src + ${CMAKE_BINARY_DIR}/googletest-build) + +enable_testing() +add_subdirectory(test) + + +## +### Cppecheck +## + +if (ENABLE_CPPCHECK) + + list(APPEND CPPCHECK_CMAKE_ARGS + "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}" + ) + include(ExternalProject) + ExternalProject_Add( + cppcheck + GIT_REPOSITORY https://github.com/danmar/cppcheck.git + GIT_TAG 1.79 + GIT_SHALLOW 1 + CMAKE_ARGS ${CPPCHECK_CMAKE_ARGS} + PREFIX ${CMAKE_BINARY_DIR}/external/cppcheck/prefix + TMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/tmp + STAMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/stamp + DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/download + SOURCE_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/src + BINARY_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/build + ) + + list(APPEND CPPCHECK_ARGS + --enable=warning,style,performance,portability,unusedFunction + --std=c99 + --verbose + --error-exitcode=1 + --language=c + -DMAIN=main + -I ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include/*.h + ${CMAKE_SOURCE_DIR}/src/*.c + ) + + add_custom_target( + check + COMMAND ${CMAKE_BINARY_DIR}/bin/cppcheck ${CPPCHECK_ARGS} + COMMENT "running cppcheck" + ) + +endif () + +## +### Source definitions ### +## + + +include_directories("${PROJECT_SOURCE_DIR}/include") + +file(GLOB sources + "${PROJECT_SOURCE_DIR}/include/*.h" + "${PROJECT_SOURCE_DIR}/src/*.c") + +add_executable(iz2 ${sources}) diff --git a/iz2/CMakeLists.txt.in b/iz2/CMakeLists.txt.in new file mode 100644 index 0000000..7499d73 --- /dev/null +++ b/iz2/CMakeLists.txt.in @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.1) + +project(extern-download NONE) + + +include(ExternalProject) +ExternalProject_Add( +googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.8.1 + SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" + BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build" + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" +) diff --git a/iz2/README.MD b/iz2/README.MD new file mode 100644 index 0000000..0b68772 --- /dev/null +++ b/iz2/README.MD @@ -0,0 +1,20 @@ +# Индивидуальное задание 1 + +ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: +* грамотное разбиение проекта на файлы; +* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; +* максимальное покрытие кода юнит-тестами; +* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами +* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью +Вариант #23 +Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + +Требования к оформлению: +Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. +Помимо самой программы необходимо: +– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; +– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. +Внимание: в основной ветке проекта никакого кода быть не должно! +– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; +– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; +– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; diff --git a/iz2/include/header.h b/iz2/include/header.h new file mode 100644 index 0000000..95b0208 --- /dev/null +++ b/iz2/include/header.h @@ -0,0 +1,3 @@ +#include + +int f(); diff --git a/iz2/src/main.c b/iz2/src/main.c new file mode 100644 index 0000000..ca9ea35 --- /dev/null +++ b/iz2/src/main.c @@ -0,0 +1,12 @@ +/* + * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» + * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на + * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + */ +#include + +int main() +{ + puts("Hello world"); + return 0; +} diff --git a/iz2/src/source.c b/iz2/src/source.c new file mode 100644 index 0000000..232d3b2 --- /dev/null +++ b/iz2/src/source.c @@ -0,0 +1,6 @@ +#include "header.h" + +int f() +{ + return 10; +} \ No newline at end of file diff --git a/iz2/test/CMakeLists.txt b/iz2/test/CMakeLists.txt new file mode 100644 index 0000000..50c75f3 --- /dev/null +++ b/iz2/test/CMakeLists.txt @@ -0,0 +1,23 @@ +include_directories("${PROJECT_SOURCE_DIR}/include") + +file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") +list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") + +file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") +list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") + +if (ENABLE_GCOV) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") +endif () + + +foreach (file ${tests}) + set(name) + get_filename_component(name ${file} NAME_WE) + add_executable("${name}_tests" + ${sources} + ${file} + "${PROJECT_SOURCE_DIR}/test/main.cpp") + target_link_libraries("${name}_tests" gtest_main) + add_test(NAME ${name} COMMAND "${name}_tests") +endforeach () \ No newline at end of file diff --git a/iz2/test/f.cpp b/iz2/test/f.cpp new file mode 100644 index 0000000..f13f6f7 --- /dev/null +++ b/iz2/test/f.cpp @@ -0,0 +1,10 @@ +#include "gtest/gtest.h" + +extern "C" { +#include "header.h" +} + +TEST(simple_test, test1) +{ + ASSERT_EQ(f(), 10); +} diff --git a/iz2/test/main.cpp b/iz2/test/main.cpp new file mode 100644 index 0000000..b42b721 --- /dev/null +++ b/iz2/test/main.cpp @@ -0,0 +1,6 @@ +#include "gtest/gtest.h" + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file From 9ffc469adcc390242e8d450e15656a83657c6789 Mon Sep 17 00:00:00 2001 From: Paul Date: Fri, 23 Oct 2020 20:13:45 +0300 Subject: [PATCH 55/65] updated readme --- iz2/README.MD | 29 +++++++++++------------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/iz2/README.MD b/iz2/README.MD index 0b68772..f5f7b4c 100644 --- a/iz2/README.MD +++ b/iz2/README.MD @@ -1,20 +1,13 @@ -# Индивидуальное задание 1 - -ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: +ИЗ2 посвящено приобретению навыков системной разработки на C и работе с внешними библиотеками. В качестве результата ИЗ2 ожидается: * грамотное разбиение проекта на файлы; -* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; -* максимальное покрытие кода юнит-тестами; -* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами -* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью +* наличие двух реализаций – последовательной и параллельной, оформленных в виде статической и динамической +библиотеки, а также тестирующей программы, которая будет сравнивать на разных входных данных результаты обеих реализаций между собой; +* максимальная утилизация ресурсов процессора при параллельной обработке данных путём использования нескольких процессов или потоков; +* продуманные структуры данных в целях экономии оперативной памяти; +* реализация алгоритмов, эффективно взаимодействующих с кэш-памятью. + Вариант #23 -Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. - -Требования к оформлению: -Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. -Помимо самой программы необходимо: -– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; -– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. -Внимание: в основной ветке проекта никакого кода быть не должно! -– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; -– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; -– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; +Сравните и выведите в консоль время работы последовательного и параллельного с использованием нескольких процессов алгоритмов, +каждый из которых выделяет в динамической памяти символьный массив размером 100 Мб и, рассматривая его содержимое как +абстрактную переписку, определяет эмоциональную окраску последней. Переписка считается оптимистичной, если +диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. From 65ee540d7da2ad5c99181e2f7adc09bc05b4b7ee Mon Sep 17 00:00:00 2001 From: Paul Date: Sat, 24 Oct 2020 19:21:21 +0300 Subject: [PATCH 56/65] moodfinder template --- iz2/examples/create.py | 9 +++++++++ iz2/include/moodfinder.h | 1 + iz2/src/main.c | 3 +++ iz2/src/moodfinder.c | 16 ++++++++++++++++ 4 files changed, 29 insertions(+) create mode 100644 iz2/examples/create.py create mode 100644 iz2/include/moodfinder.h create mode 100644 iz2/src/moodfinder.c diff --git a/iz2/examples/create.py b/iz2/examples/create.py new file mode 100644 index 0000000..870a684 --- /dev/null +++ b/iz2/examples/create.py @@ -0,0 +1,9 @@ +import random +import sys + +alphabet = 'abc:()' +with open(sys.argv[1], 'w') as file: + for i in range(int(sys.argv[2])): + file.write(alphabet[random.randint(0, len(alphabet) - 1)]) + + diff --git a/iz2/include/moodfinder.h b/iz2/include/moodfinder.h new file mode 100644 index 0000000..669a626 --- /dev/null +++ b/iz2/include/moodfinder.h @@ -0,0 +1 @@ +int find_mood(const char *filename); \ No newline at end of file diff --git a/iz2/src/main.c b/iz2/src/main.c index ca9ea35..212bea4 100644 --- a/iz2/src/main.c +++ b/iz2/src/main.c @@ -4,9 +4,12 @@ * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. */ #include +#include "moodfinder.h" int main() { puts("Hello world"); + char filename[] = "../examples/f.txt"; + printf("Mood of %s is %d\n", filename, find_mood(filename)); return 0; } diff --git a/iz2/src/moodfinder.c b/iz2/src/moodfinder.c new file mode 100644 index 0000000..771f332 --- /dev/null +++ b/iz2/src/moodfinder.c @@ -0,0 +1,16 @@ +#include "moodfinder.h" + +#include +#include +#include +#include + +int find_mood(const char *filename) +{ + struct stat st; + if (stat(filename, &st)) + return 0; + + char *file = (char *)malloc(st.st_size); + return st.st_size; +} From 1ad36091425cc63e4953d559ed4501f25e852964 Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 27 Oct 2020 16:31:55 +0300 Subject: [PATCH 57/65] updated .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f3b51ca..c5f07d8 100644 --- a/.gitignore +++ b/.gitignore @@ -34,4 +34,5 @@ # Macos things *.DS_Store *.idea/ -*cmake-build-debug +*cmake-build* + From e2ce8e914fcd99c22975e9fe77076d40646e639e Mon Sep 17 00:00:00 2001 From: Paul Date: Tue, 27 Oct 2020 16:32:29 +0300 Subject: [PATCH 58/65] Single process version + tests --- iz2/CMakeLists.txt | 70 ++----------------- iz2/examples/clear_negative.txt | 1 + iz2/examples/clear_positive.txt | 1 + iz2/examples/create.py | 2 - iz2/examples/dirty_negative.txt | 1 + iz2/examples/dirty_positive.txt | 1 + iz2/examples/script.py | 11 +++ iz2/include/header.h | 3 - iz2/include/moodfinder.h | 5 +- ...{CMakeLists.txt.in => install_gtest.cmake} | 8 +-- iz2/src/main.c | 64 ++++++++++++++--- iz2/src/moodfinder.c | 33 +++++++-- iz2/src/source.c | 6 -- iz2/test/CMakeLists.txt | 2 + iz2/test/f.cpp | 10 --- iz2/test/moodfinder.cpp | 41 +++++++++++ 16 files changed, 154 insertions(+), 105 deletions(-) create mode 100644 iz2/examples/clear_negative.txt create mode 100644 iz2/examples/clear_positive.txt create mode 100644 iz2/examples/dirty_negative.txt create mode 100644 iz2/examples/dirty_positive.txt create mode 100644 iz2/examples/script.py delete mode 100644 iz2/include/header.h rename iz2/{CMakeLists.txt.in => install_gtest.cmake} (84%) delete mode 100644 iz2/src/source.c delete mode 100644 iz2/test/f.cpp create mode 100644 iz2/test/moodfinder.cpp diff --git a/iz2/CMakeLists.txt b/iz2/CMakeLists.txt index 300d1c9..e3a4b27 100644 --- a/iz2/CMakeLists.txt +++ b/iz2/CMakeLists.txt @@ -6,37 +6,27 @@ set(CMAKE_C_STANDARD 99) set(CMAKE_CXX_STANDARD 17) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -# -### GCOV -# - -if (ENABLE_GCOV) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") -endif () - - ## ### Valgrind ## - +# set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") - - +# ## ### Test definitions ### ## - +# include(CTest) - -configure_file(CMakeLists.txt.in +# +configure_file(install_gtest.cmake googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) execute_process(COMMAND ${CMAKE_COMMAND} --build . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src ${CMAKE_BINARY_DIR}/googletest-build) @@ -45,53 +35,7 @@ enable_testing() add_subdirectory(test) -## -### Cppecheck -## - -if (ENABLE_CPPCHECK) - - list(APPEND CPPCHECK_CMAKE_ARGS - "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}" - ) - include(ExternalProject) - ExternalProject_Add( - cppcheck - GIT_REPOSITORY https://github.com/danmar/cppcheck.git - GIT_TAG 1.79 - GIT_SHALLOW 1 - CMAKE_ARGS ${CPPCHECK_CMAKE_ARGS} - PREFIX ${CMAKE_BINARY_DIR}/external/cppcheck/prefix - TMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/tmp - STAMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/stamp - DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/download - SOURCE_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/src - BINARY_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/build - ) - - list(APPEND CPPCHECK_ARGS - --enable=warning,style,performance,portability,unusedFunction - --std=c99 - --verbose - --error-exitcode=1 - --language=c - -DMAIN=main - -I ${CMAKE_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/include/*.h - ${CMAKE_SOURCE_DIR}/src/*.c - ) - - add_custom_target( - check - COMMAND ${CMAKE_BINARY_DIR}/bin/cppcheck ${CPPCHECK_ARGS} - COMMENT "running cppcheck" - ) - -endif () - -## ### Source definitions ### -## include_directories("${PROJECT_SOURCE_DIR}/include") diff --git a/iz2/examples/clear_negative.txt b/iz2/examples/clear_negative.txt new file mode 100644 index 0000000..44a075c --- /dev/null +++ b/iz2/examples/clear_negative.txt @@ -0,0 +1 @@ +:(:(:(:(:(:(:(:(:(:(:(:(:(:(:(:(:(:(:(:( \ No newline at end of file diff --git a/iz2/examples/clear_positive.txt b/iz2/examples/clear_positive.txt new file mode 100644 index 0000000..0126061 --- /dev/null +++ b/iz2/examples/clear_positive.txt @@ -0,0 +1 @@ +:):):):):):):):):):):):):):):):):):):):) \ No newline at end of file diff --git a/iz2/examples/create.py b/iz2/examples/create.py index 870a684..e4a7086 100644 --- a/iz2/examples/create.py +++ b/iz2/examples/create.py @@ -5,5 +5,3 @@ with open(sys.argv[1], 'w') as file: for i in range(int(sys.argv[2])): file.write(alphabet[random.randint(0, len(alphabet) - 1)]) - - diff --git a/iz2/examples/dirty_negative.txt b/iz2/examples/dirty_negative.txt new file mode 100644 index 0000000..fb1a4d6 --- /dev/null +++ b/iz2/examples/dirty_negative.txt @@ -0,0 +1 @@ +bpserqn:(grlbmyauwo:(flvvyw:(dt:(gtroemwi:(yflxrv:(vr:(nbaqwvbbxd:(:(fet:(zincficm:(rgozemxfw:(cwof:(rxrm:(zont:(gtufqcw:(:(ynydxbpox:(dmbjefj:(hwovhqxh:( \ No newline at end of file diff --git a/iz2/examples/dirty_positive.txt b/iz2/examples/dirty_positive.txt new file mode 100644 index 0000000..5acb75f --- /dev/null +++ b/iz2/examples/dirty_positive.txt @@ -0,0 +1 @@ +liaki:)bcnq:)uwh:)qnexbr:):)cxojtrerwb:)dj:)leag:)iw:)qlwstugh:)shjckmyao:)ssjhbxqd:)zcpihlvf:)ipfjwra:)f:)is:)tyx:):)tqfhe:)lkpixd:) \ No newline at end of file diff --git a/iz2/examples/script.py b/iz2/examples/script.py new file mode 100644 index 0000000..dfd93fc --- /dev/null +++ b/iz2/examples/script.py @@ -0,0 +1,11 @@ +import string +import random + +f = open('dirty_negative.txt', 'w') +letters = string.ascii_lowercase + +for _ in range(20): + f.write(''.join([letters[random.randint(0, len(letters) - 1)] for i in range(random.randint(0, 10))])) + f.write(':(') + +f.close() diff --git a/iz2/include/header.h b/iz2/include/header.h deleted file mode 100644 index 95b0208..0000000 --- a/iz2/include/header.h +++ /dev/null @@ -1,3 +0,0 @@ -#include - -int f(); diff --git a/iz2/include/moodfinder.h b/iz2/include/moodfinder.h index 669a626..b62116b 100644 --- a/iz2/include/moodfinder.h +++ b/iz2/include/moodfinder.h @@ -1 +1,4 @@ -int find_mood(const char *filename); \ No newline at end of file +#define POSITIVE 0 +#define NEGATIVE 1 + +int find_mood(const char *filename); diff --git a/iz2/CMakeLists.txt.in b/iz2/install_gtest.cmake similarity index 84% rename from iz2/CMakeLists.txt.in rename to iz2/install_gtest.cmake index 7499d73..586d9d6 100644 --- a/iz2/CMakeLists.txt.in +++ b/iz2/install_gtest.cmake @@ -1,11 +1,9 @@ cmake_minimum_required(VERSION 3.1) -project(extern-download NONE) - +project(googletest-download NONE) include(ExternalProject) -ExternalProject_Add( -googletest +ExternalProject_Add(googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.8.1 SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" @@ -14,4 +12,4 @@ googletest BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" -) +) \ No newline at end of file diff --git a/iz2/src/main.c b/iz2/src/main.c index 212bea4..28d053d 100644 --- a/iz2/src/main.c +++ b/iz2/src/main.c @@ -1,15 +1,63 @@ /* - * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» - * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на - * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. +Сравните и выведите в консоль время работы последовательного и параллельного с использованием +нескольких процессов алгоритмов, каждый из которых выделяет в динамической памяти символьный +массив размером 100 Мб и, рассматривая его содержимое как абстрактную переписку, определяет +эмоциональную окраску последней. Переписка считается оптимистичной, если диграфов :) в ней +больше, чем диграфов :(; в противном случае переписка признается пессимистичной. */ + +#include #include -#include "moodfinder.h" +#include +#include +#include +#include +#include int main() { - puts("Hello world"); - char filename[] = "../examples/f.txt"; - printf("Mood of %s is %d\n", filename, find_mood(filename)); - return 0; + static const char *filename = "../examples/f.txt"; + char replacing_symbol = 'A'; + + /* + FILE *f = fopen(filename, "r"); + int fd = fileno(f); + */ + int fd = open(filename, O_RDONLY); // или O_RDWR + struct stat st; + stat(filename, &st); + + size_t file_size = st.st_size; + + // PROT_READ - чтение; PROT_WRITE - чтение/запись + // MAP_PRIVATE - не записывать в файл; + // MAP_POPULATE - предзагрузка файла ядром; + // MAP_SHARED - деление с другими процессами + char *region = mmap(NULL, + file_size, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_POPULATE, + fd, + 0); + if (region == MAP_FAILED) + { + printf("mmap failed\n"); + close(fd); + return 1; + } + + printf("What was read\n"); + write(fileno(stdout), region, file_size); // fileno(stdout) == 1 + + for (size_t i = 0; i < file_size; ++i) + { region[i] = replacing_symbol; } + + printf("After modification: %s\n", region); + + if (munmap(region, file_size) != 0) + { + printf("munmap failed\n"); + } + + close(fd); } diff --git a/iz2/src/moodfinder.c b/iz2/src/moodfinder.c index 771f332..d86640e 100644 --- a/iz2/src/moodfinder.c +++ b/iz2/src/moodfinder.c @@ -1,16 +1,35 @@ #include "moodfinder.h" +#include #include -#include -#include #include +#include +#include + int find_mood(const char *filename) { + int fd = open(filename, O_RDONLY); struct stat st; - if (stat(filename, &st)) - return 0; - - char *file = (char *)malloc(st.st_size); - return st.st_size; + stat(filename, &st); + size_t file_size = st.st_size; + char *region = mmap(NULL, + file_size, + PROT_READ, + (unsigned) MAP_SHARED | (unsigned) MAP_POPULATE, + fd, + 0); + if (region == MAP_FAILED) + { + printf("mmap failed\n"); + close(fd); + return -1; + } + long long mood = 0; + for (size_t i = 0; i < file_size - 1; ++i) + { + if (region[i] == ':') + mood += (region[i + 1] == ')') + -1 * (region[i + 1] == '('); + } + return mood > 0 ? POSITIVE : NEGATIVE; } diff --git a/iz2/src/source.c b/iz2/src/source.c deleted file mode 100644 index 232d3b2..0000000 --- a/iz2/src/source.c +++ /dev/null @@ -1,6 +0,0 @@ -#include "header.h" - -int f() -{ - return 10; -} \ No newline at end of file diff --git a/iz2/test/CMakeLists.txt b/iz2/test/CMakeLists.txt index 50c75f3..518f126 100644 --- a/iz2/test/CMakeLists.txt +++ b/iz2/test/CMakeLists.txt @@ -1,3 +1,5 @@ +cmake_minimum_required(VERSION 3.1) + include_directories("${PROJECT_SOURCE_DIR}/include") file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") diff --git a/iz2/test/f.cpp b/iz2/test/f.cpp deleted file mode 100644 index f13f6f7..0000000 --- a/iz2/test/f.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "gtest/gtest.h" - -extern "C" { -#include "header.h" -} - -TEST(simple_test, test1) -{ - ASSERT_EQ(f(), 10); -} diff --git a/iz2/test/moodfinder.cpp b/iz2/test/moodfinder.cpp new file mode 100644 index 0000000..fa4cfae --- /dev/null +++ b/iz2/test/moodfinder.cpp @@ -0,0 +1,41 @@ +#include "gtest/gtest.h" +#include +#include + +using namespace std; + + +string construct_path(const string &filename) +{ + const static string examples = "./examples/"; + return examples + filename; +} + +extern "C" { +#include "moodfinder.h" +} + +TEST(find_mood_positive, clear) +{ + const string filename = "clear_positive.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), POSITIVE); +} + +TEST(find_mood_positive, dirty) +{ + const string filename = "dirty_positive.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), POSITIVE); +} + +TEST(find_mood_negative, clear) +{ + const string filename = "clear_negative.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), NEGATIVE); +} + +TEST(find_mood_negative, dirty) +{ + const string filename = "dirty_negative.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), NEGATIVE); +} + From be5966c35bf7cbd17632360e3e806f1c775949d2 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 10:21:55 +0300 Subject: [PATCH 59/65] singleprocess working" --- iz2/CMakeLists.txt | 55 ++++++++++---------- iz2/README.MD | 29 +++++++---- iz2/configure_cppcheck.cmake | 39 ++++++++++++++ iz2/configure_test.cmake | 26 ++++++++++ iz2/examples/create.py | 7 --- iz2/examples/empty.txt | 0 iz2/examples/neutral.txt | 1 + iz2/examples/script.py | 14 ++--- iz2/include/moodfinder.h | 1 + iz2/install_gtest.cmake | 8 +-- iz2/src/main.c | 65 +++++------------------- iz2/src/{moodfinder.c => moodfinder_s.c} | 6 +-- iz2/test/CMakeLists.txt | 11 ++-- iz2/test/main.cpp | 0 iz2/test/moodfinder.cpp | 11 ++++ 15 files changed, 155 insertions(+), 118 deletions(-) mode change 100644 => 100755 iz2/CMakeLists.txt mode change 100644 => 100755 iz2/README.MD create mode 100644 iz2/configure_cppcheck.cmake create mode 100644 iz2/configure_test.cmake delete mode 100644 iz2/examples/create.py create mode 100644 iz2/examples/empty.txt create mode 100644 iz2/examples/neutral.txt mode change 100644 => 100755 iz2/install_gtest.cmake rename iz2/src/{moodfinder.c => moodfinder_s.c} (90%) mode change 100644 => 100755 iz2/test/CMakeLists.txt mode change 100644 => 100755 iz2/test/main.cpp diff --git a/iz2/CMakeLists.txt b/iz2/CMakeLists.txt old mode 100644 new mode 100755 index e3a4b27..733be47 --- a/iz2/CMakeLists.txt +++ b/iz2/CMakeLists.txt @@ -1,47 +1,44 @@ cmake_minimum_required(VERSION 3.1) -project(iz2 C CXX) +project(iz1 C CXX) set(CMAKE_C_STANDARD 99) set(CMAKE_CXX_STANDARD 17) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -## -### Valgrind -## -# -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") -# -## -### Test definitions ### -## # -include(CTest) +### GCOV # -configure_file(install_gtest.cmake - googletest-download/CMakeLists.txt) -execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) -execute_process(COMMAND ${CMAKE_COMMAND} --build . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download ) -add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src - ${CMAKE_BINARY_DIR}/googletest-build) +if (ENABLE_GCOV) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") +endif () -enable_testing() + +include(configure_test.cmake) add_subdirectory(test) +if (ENABLE_CPPCHECK) + include(configure_cppcheck.cmake) +endif () +## ### Source definitions ### +## + +set(libmoodfinder_s_sources + ${PROJECT_SOURCE_DIR}/include/moodfinder.h + ${PROJECT_SOURCE_DIR}/src/moodfinder_s.c + ) include_directories("${PROJECT_SOURCE_DIR}/include") -file(GLOB sources - "${PROJECT_SOURCE_DIR}/include/*.h" - "${PROJECT_SOURCE_DIR}/src/*.c") +add_library(libmoodfinder_s STATIC ${libmoodfinder_s_sources}) + +set(main_sources + ${PROJECT_SOURCE_DIR}/src/main.c + ) + +add_executable(main ${main_sources}) +target_link_libraries(main libmoodfinder_s) + -add_executable(iz2 ${sources}) diff --git a/iz2/README.MD b/iz2/README.MD old mode 100644 new mode 100755 index f5f7b4c..0b68772 --- a/iz2/README.MD +++ b/iz2/README.MD @@ -1,13 +1,20 @@ -ИЗ2 посвящено приобретению навыков системной разработки на C и работе с внешними библиотеками. В качестве результата ИЗ2 ожидается: +# Индивидуальное задание 1 + +ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: * грамотное разбиение проекта на файлы; -* наличие двух реализаций – последовательной и параллельной, оформленных в виде статической и динамической -библиотеки, а также тестирующей программы, которая будет сравнивать на разных входных данных результаты обеих реализаций между собой; -* максимальная утилизация ресурсов процессора при параллельной обработке данных путём использования нескольких процессов или потоков; -* продуманные структуры данных в целях экономии оперативной памяти; -* реализация алгоритмов, эффективно взаимодействующих с кэш-памятью. - +* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; +* максимальное покрытие кода юнит-тестами; +* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами +* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью Вариант #23 -Сравните и выведите в консоль время работы последовательного и параллельного с использованием нескольких процессов алгоритмов, -каждый из которых выделяет в динамической памяти символьный массив размером 100 Мб и, рассматривая его содержимое как -абстрактную переписку, определяет эмоциональную окраску последней. Переписка считается оптимистичной, если -диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. +Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. + +Требования к оформлению: +Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. +Помимо самой программы необходимо: +– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; +– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. +Внимание: в основной ветке проекта никакого кода быть не должно! +– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; +– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; +– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; diff --git a/iz2/configure_cppcheck.cmake b/iz2/configure_cppcheck.cmake new file mode 100644 index 0000000..66c9030 --- /dev/null +++ b/iz2/configure_cppcheck.cmake @@ -0,0 +1,39 @@ +## +### Cppcheck +## + +list(APPEND CPPCHECK_CMAKE_ARGS + "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}" + ) +include(ExternalProject) +ExternalProject_Add( + cppcheck + GIT_REPOSITORY https://github.com/danmar/cppcheck.git + GIT_TAG 1.79 + GIT_SHALLOW 1 + CMAKE_ARGS ${CPPCHECK_CMAKE_ARGS} + PREFIX ${CMAKE_BINARY_DIR}/external/cppcheck/prefix + TMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/tmp + STAMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/stamp + DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/download + SOURCE_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/src + BINARY_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/build +) + +list(APPEND CPPCHECK_ARGS + --enable=warning,style,performance,portability,unusedFunction + --std=c99 + --verbose + --error-exitcode=1 + --language=c + -DMAIN=main + -I ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include/*.h + ${CMAKE_SOURCE_DIR}/src/*.c + ) + +add_custom_target( + check + COMMAND ${CMAKE_BINARY_DIR}/bin/cppcheck ${CPPCHECK_ARGS} + COMMENT "running cppcheck" +) diff --git a/iz2/configure_test.cmake b/iz2/configure_test.cmake new file mode 100644 index 0000000..6406a9e --- /dev/null +++ b/iz2/configure_test.cmake @@ -0,0 +1,26 @@ +## +### Valgrind +## + +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") +set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") + +## +### Test definitions ### +## +include(CTest) + +configure_file(install_gtest.cmake + googletest-download/CMakeLists.txt) +execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) +execute_process(COMMAND ${CMAKE_COMMAND} --build . + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) + +add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src + ${CMAKE_BINARY_DIR}/googletest-build) + +enable_testing() + diff --git a/iz2/examples/create.py b/iz2/examples/create.py deleted file mode 100644 index e4a7086..0000000 --- a/iz2/examples/create.py +++ /dev/null @@ -1,7 +0,0 @@ -import random -import sys - -alphabet = 'abc:()' -with open(sys.argv[1], 'w') as file: - for i in range(int(sys.argv[2])): - file.write(alphabet[random.randint(0, len(alphabet) - 1)]) diff --git a/iz2/examples/empty.txt b/iz2/examples/empty.txt new file mode 100644 index 0000000..e69de29 diff --git a/iz2/examples/neutral.txt b/iz2/examples/neutral.txt new file mode 100644 index 0000000..140f766 --- /dev/null +++ b/iz2/examples/neutral.txt @@ -0,0 +1 @@ +:)hfc:(:)viexcm:(:):(:)veux:(:)xyomlgochx:(:)hkewbzhym:(:):(:)llu:(:):(:)wrrtzwhqgm:(:)qyxgxhesw:(:):(:)bdbhvwizxw:(:)ugfosxx:(:)oxs:(:)uwbfjeor:(:)kunsgh:(:)jpat:(:)f:(:)zqgotu:(:)skirkrregh:(:)mqo:(:)giuex:(:)uoz:(:)unedk:(:)ummgxloei:(:)pfvzxogd:(:)oottuozmew:(:)yadwlltyv:(:)ai:(:)zcvgdvou:(:)pw:(:)ww:(:)ptlrtm:(:)skdyh:(:)tovzyh:(:)ssgdchl:(:)tqqmkzd:(:)jdo:(:)qbfgusxuvk:(:):(:)pyo:(:)hnt:(:)dxkpznror:(:)iotfc:(:):(:)akyyyf:(:)oow:(:)guthbyfy:(:)yfxckx:(:)aqoorhxlvx:(:)jtikbnbnvd:(:)psffqnyiq:(:)vvcs:(:)eteraparaa:(:)jtxfwq:(:):(:)s:(:)ueciggoy:(:)wrwjmoda:(:):(:)sdsejmg:(:)yxotncs:(:)ddkjgb:(:)fn:(:)acjh:(:)toim:(:)swtu:(:)tglz:(:)mglvoj:(:)w:(:)htllhw:(:)sazwfryjew:(:)xbwaiz:(:)ofullgdip:(:)gkfgccf:(:)ejdptbb:(:)exqucqrrn:(:)sh:(:)sdcjuww:(:)nnffdp:(:):(:)qky:(:)qajnys:(:)qbntjbm:(:):(:)iutbwcaec:(:)zitjp:(:)bmsgjyfmo:(:)uizgq:(:)rasrxet:(:)ruy:(:):(:)gczhefir:(:)mwnhxkzxvj:(:)eb:(:)icw:(:)bdlnlbz:(:)wzyr:(:)kzvuwpu:( \ No newline at end of file diff --git a/iz2/examples/script.py b/iz2/examples/script.py index dfd93fc..4ff7994 100644 --- a/iz2/examples/script.py +++ b/iz2/examples/script.py @@ -1,11 +1,11 @@ import string import random -f = open('dirty_negative.txt', 'w') +file = open('neutral.txt', 'w') letters = string.ascii_lowercase - -for _ in range(20): - f.write(''.join([letters[random.randint(0, len(letters) - 1)] for i in range(random.randint(0, 10))])) - f.write(':(') - -f.close() +count = 100 +for _ in range(count): + file.write(':)') + file.write(''.join([letters[random.randint(0, len(letters) - 1)] for i in range(random.randint(0, 10))])) + file.write(':(') +file.close() diff --git a/iz2/include/moodfinder.h b/iz2/include/moodfinder.h index b62116b..d310cfa 100644 --- a/iz2/include/moodfinder.h +++ b/iz2/include/moodfinder.h @@ -1,4 +1,5 @@ #define POSITIVE 0 #define NEGATIVE 1 +#define NEUTRAL 2 int find_mood(const char *filename); diff --git a/iz2/install_gtest.cmake b/iz2/install_gtest.cmake old mode 100644 new mode 100755 index 586d9d6..7499d73 --- a/iz2/install_gtest.cmake +++ b/iz2/install_gtest.cmake @@ -1,9 +1,11 @@ cmake_minimum_required(VERSION 3.1) -project(googletest-download NONE) +project(extern-download NONE) + include(ExternalProject) -ExternalProject_Add(googletest +ExternalProject_Add( +googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG release-1.8.1 SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" @@ -12,4 +14,4 @@ ExternalProject_Add(googletest BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" -) \ No newline at end of file +) diff --git a/iz2/src/main.c b/iz2/src/main.c index 28d053d..4023a5f 100644 --- a/iz2/src/main.c +++ b/iz2/src/main.c @@ -6,58 +6,21 @@ больше, чем диграфов :(; в противном случае переписка признается пессимистичной. */ -#include +#include "moodfinder.h" +#include #include -#include -#include -#include -#include -#include -int main() +int main(int argc, char *argv[]) { - static const char *filename = "../examples/f.txt"; - char replacing_symbol = 'A'; - - /* - FILE *f = fopen(filename, "r"); - int fd = fileno(f); - */ - int fd = open(filename, O_RDONLY); // или O_RDWR - struct stat st; - stat(filename, &st); - - size_t file_size = st.st_size; - - // PROT_READ - чтение; PROT_WRITE - чтение/запись - // MAP_PRIVATE - не записывать в файл; - // MAP_POPULATE - предзагрузка файла ядром; - // MAP_SHARED - деление с другими процессами - char *region = mmap(NULL, - file_size, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_POPULATE, - fd, - 0); - if (region == MAP_FAILED) - { - printf("mmap failed\n"); - close(fd); - return 1; - } - - printf("What was read\n"); - write(fileno(stdout), region, file_size); // fileno(stdout) == 1 - - for (size_t i = 0; i < file_size; ++i) - { region[i] = replacing_symbol; } - - printf("After modification: %s\n", region); - - if (munmap(region, file_size) != 0) - { - printf("munmap failed\n"); - } - - close(fd); + struct timespec start, finish; + double elapsed; + clock_gettime(CLOCK_MONOTONIC, &start); + int mood = find_mood(argv[1]); + clock_gettime(CLOCK_MONOTONIC, &finish); + if (mood != -1) + printf("Mood: %d\n", mood); + elapsed = (double)(finish.tv_sec - start.tv_sec); + elapsed += (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; + printf("Work time: %lf\n", elapsed); + return 0; } diff --git a/iz2/src/moodfinder.c b/iz2/src/moodfinder_s.c similarity index 90% rename from iz2/src/moodfinder.c rename to iz2/src/moodfinder_s.c index d86640e..f5b6127 100644 --- a/iz2/src/moodfinder.c +++ b/iz2/src/moodfinder_s.c @@ -21,7 +21,6 @@ int find_mood(const char *filename) 0); if (region == MAP_FAILED) { - printf("mmap failed\n"); close(fd); return -1; } @@ -31,5 +30,6 @@ int find_mood(const char *filename) if (region[i] == ':') mood += (region[i + 1] == ')') + -1 * (region[i + 1] == '('); } - return mood > 0 ? POSITIVE : NEGATIVE; -} + close(fd); + return mood > 0 ? POSITIVE : (mood == 0 ? NEUTRAL : NEGATIVE); +} \ No newline at end of file diff --git a/iz2/test/CMakeLists.txt b/iz2/test/CMakeLists.txt old mode 100644 new mode 100755 index 518f126..16de5cc --- a/iz2/test/CMakeLists.txt +++ b/iz2/test/CMakeLists.txt @@ -1,10 +1,5 @@ -cmake_minimum_required(VERSION 3.1) - include_directories("${PROJECT_SOURCE_DIR}/include") -file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") -list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") - file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") @@ -17,9 +12,11 @@ foreach (file ${tests}) set(name) get_filename_component(name ${file} NAME_WE) add_executable("${name}_tests" - ${sources} ${file} "${PROJECT_SOURCE_DIR}/test/main.cpp") - target_link_libraries("${name}_tests" gtest_main) + target_link_libraries("${name}_tests" + libmoodfinder_s + gtest_main + ) add_test(NAME ${name} COMMAND "${name}_tests") endforeach () \ No newline at end of file diff --git a/iz2/test/main.cpp b/iz2/test/main.cpp old mode 100644 new mode 100755 diff --git a/iz2/test/moodfinder.cpp b/iz2/test/moodfinder.cpp index fa4cfae..05e7180 100644 --- a/iz2/test/moodfinder.cpp +++ b/iz2/test/moodfinder.cpp @@ -39,3 +39,14 @@ TEST(find_mood_negative, dirty) ASSERT_EQ(find_mood(construct_path(filename).c_str()), NEGATIVE); } +TEST(find_mood_neutral, dirty) +{ + const string filename = "neutral.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), NEUTRAL); +} + +TEST(find_mood_errors, empty) +{ + const string filename = "empty.txt"; + ASSERT_EQ(find_mood(construct_path(filename).c_str()), -1); +} \ No newline at end of file From f68802cf530b3f1098fb62a80f928ecfd0d0d714 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 10:23:03 +0300 Subject: [PATCH 60/65] updated travis --- .travis.yml | 2 +- iz1/CMakeLists.txt | 104 ----------------------- iz1/CMakeLists.txt.in | 17 ---- iz1/README.MD | 20 ----- iz1/include/html_tag/attr.h | 24 ------ iz1/include/html_tag/html_tag.h | 39 --------- iz1/include/my_str/alg.h | 12 --- iz1/include/my_str/mem.h | 12 --- iz1/src/alg.c | 34 -------- iz1/src/attr.c | 68 --------------- iz1/src/html_tag.c | 87 -------------------- iz1/src/main.c | 35 -------- iz1/src/mem.c | 30 ------- iz1/test/CMakeLists.txt | 23 ------ iz1/test/attr.cpp | 42 ---------- iz1/test/check_attr_format.cpp | 63 -------------- iz1/test/check_html_tag_format.cpp | 93 --------------------- iz1/test/html_tag.cpp | 127 ----------------------------- iz1/test/main.cpp | 6 -- 19 files changed, 1 insertion(+), 837 deletions(-) delete mode 100644 iz1/CMakeLists.txt delete mode 100644 iz1/CMakeLists.txt.in delete mode 100644 iz1/README.MD delete mode 100644 iz1/include/html_tag/attr.h delete mode 100644 iz1/include/html_tag/html_tag.h delete mode 100644 iz1/include/my_str/alg.h delete mode 100644 iz1/include/my_str/mem.h delete mode 100644 iz1/src/alg.c delete mode 100644 iz1/src/attr.c delete mode 100644 iz1/src/html_tag.c delete mode 100644 iz1/src/main.c delete mode 100644 iz1/src/mem.c delete mode 100644 iz1/test/CMakeLists.txt delete mode 100644 iz1/test/attr.cpp delete mode 100644 iz1/test/check_attr_format.cpp delete mode 100644 iz1/test/check_html_tag_format.cpp delete mode 100644 iz1/test/html_tag.cpp delete mode 100644 iz1/test/main.cpp diff --git a/.travis.yml b/.travis.yml index 960be4d..656b5a4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ compiler: gcc before_script: - - cd iz1 + - cd iz2 - mkdir build - cd build diff --git a/iz1/CMakeLists.txt b/iz1/CMakeLists.txt deleted file mode 100644 index 4cb7fee..0000000 --- a/iz1/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -cmake_minimum_required(VERSION 3.1) - -project(iz1 C CXX) - -set(CMAKE_C_STANDARD 99) -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -# -### GCOV -# - -if (ENABLE_GCOV) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") -endif () - - -## -### Valgrind -## - -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --leak-check=full") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --track-fds=yes") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --trace-children=yes") -set(MEMORYCHECK_COMMAND_OPTIONS "${MEMORYCHECK_COMMAND_OPTIONS} --error-exitcode=1") - - -## -### Test definitions ### -## - -include(CTest) - -configure_file(CMakeLists.txt.in - googletest-download/CMakeLists.txt) -execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) -execute_process(COMMAND ${CMAKE_COMMAND} --build . - WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/googletest-download) - -add_subdirectory(${CMAKE_BINARY_DIR}/googletest-src - ${CMAKE_BINARY_DIR}/googletest-build) - -enable_testing() -add_subdirectory(test) - - -## -### Cppecheck -## - -if (ENABLE_CPPCHECK) - - list(APPEND CPPCHECK_CMAKE_ARGS - "-DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}" - ) - include(ExternalProject) - ExternalProject_Add( - cppcheck - GIT_REPOSITORY https://github.com/danmar/cppcheck.git - GIT_TAG 1.79 - GIT_SHALLOW 1 - CMAKE_ARGS ${CPPCHECK_CMAKE_ARGS} - PREFIX ${CMAKE_BINARY_DIR}/external/cppcheck/prefix - TMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/tmp - STAMP_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/stamp - DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/download - SOURCE_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/src - BINARY_DIR ${CMAKE_BINARY_DIR}/external/cppcheck/build - ) - - list(APPEND CPPCHECK_ARGS - --enable=warning,style,performance,portability,unusedFunction - --std=c99 - --verbose - --error-exitcode=1 - --language=c - -DMAIN=main - -I ${CMAKE_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/include/*.h - ${CMAKE_SOURCE_DIR}/src/*.c - ) - - add_custom_target( - check - COMMAND ${CMAKE_BINARY_DIR}/bin/cppcheck ${CPPCHECK_ARGS} - COMMENT "running cppcheck" - ) - -endif () - -## -### Source definitions ### -## - - -include_directories("${PROJECT_SOURCE_DIR}/include") - -file(GLOB sources - "${PROJECT_SOURCE_DIR}/include/html_tag/*.h" - "${PROJECT_SOURCE_DIR}/include/my_str/*.h" - "${PROJECT_SOURCE_DIR}/src/*.c") - -add_executable(iz1 ${sources}) diff --git a/iz1/CMakeLists.txt.in b/iz1/CMakeLists.txt.in deleted file mode 100644 index 7499d73..0000000 --- a/iz1/CMakeLists.txt.in +++ /dev/null @@ -1,17 +0,0 @@ -cmake_minimum_required(VERSION 3.1) - -project(extern-download NONE) - - -include(ExternalProject) -ExternalProject_Add( -googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG release-1.8.1 - SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" - BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build" - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - TEST_COMMAND "" -) diff --git a/iz1/README.MD b/iz1/README.MD deleted file mode 100644 index 0b68772..0000000 --- a/iz1/README.MD +++ /dev/null @@ -1,20 +0,0 @@ -# Индивидуальное задание 1 - -ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: -* грамотное разбиение проекта на файлы; -* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; -* максимальное покрытие кода юнит-тестами; -* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами -* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью -Вариант #23 -Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. - -Требования к оформлению: -Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. -Помимо самой программы необходимо: -– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; -– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. -Внимание: в основной ветке проекта никакого кода быть не должно! -– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; -– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; -– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; diff --git a/iz1/include/html_tag/attr.h b/iz1/include/html_tag/attr.h deleted file mode 100644 index d4ecce5..0000000 --- a/iz1/include/html_tag/attr.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef IZ1_ATTR_H -#define IZ1_ATTR_H - -#include -#include - -typedef struct -{ - char *name; - char *value; -} tag_attr_t; - -// Функция проверки аттрибута тега (тег располагается в начале строкии и -// заканчивается либо символом '>', либо пробелом. Конец аттрибута записывается -// в переменную attr_end -bool check_attr_format(const char *str, size_t *attr_end); - -tag_attr_t *parse_attr(const char *str, int *attr_end); - -tag_attr_t **parse_attr_arr(const char *str, size_t count); - -void free_attr(tag_attr_t **attr); - -#endif //IZ1_ATTR_H diff --git a/iz1/include/html_tag/html_tag.h b/iz1/include/html_tag/html_tag.h deleted file mode 100644 index 439552e..0000000 --- a/iz1/include/html_tag/html_tag.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» - * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на - * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. - * - * Примеры тегов - * - * - * - * - * - * - */ - -#ifndef IZ1_HTML_TAG_H -#define IZ1_HTML_TAG_H - -#include -#include - -#include "attr.h" - -typedef struct -{ - char *name; - bool is_opening; - size_t attributes_count; - tag_attr_t **attributes; -} html_tag; - -bool check_html_tag_format(const char *str); - -html_tag *parse_tag(const char *str); - -size_t parse_status(const char *str, html_tag *tag); - -void free_tag(html_tag **tag); - -#endif //IZ1_HTML_TAG_H diff --git a/iz1/include/my_str/alg.h b/iz1/include/my_str/alg.h deleted file mode 100644 index 0ce08e4..0000000 --- a/iz1/include/my_str/alg.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef IZ1_ALG_H -#define IZ1_ALG_H - -#define ASCII_NAME_ALLOWED "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789\"-" - -int str_find(const char *str, char c); - -int str_first_char_occurence(const char *str, const char *c); - -int str_count(const char *str, char c); - -#endif //IZ1_ALG_H diff --git a/iz1/include/my_str/mem.h b/iz1/include/my_str/mem.h deleted file mode 100644 index 216f72f..0000000 --- a/iz1/include/my_str/mem.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef IZ1_MEM_H -#define IZ1_MEM_H - -#include -#include - - -size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n); - -size_t str_create_word(char **to_allocate, const char *src, const char *sep); - -#endif //IZ1_MEM_H diff --git a/iz1/src/alg.c b/iz1/src/alg.c deleted file mode 100644 index 2b2cedd..0000000 --- a/iz1/src/alg.c +++ /dev/null @@ -1,34 +0,0 @@ -#include "my_str/alg.h" - -int str_find(const char *str, char c) -{ - if (!str) - return -1; - - int i = 0; - while (str[i] != c && str[i] != '\0') - ++i; - return i; -} - -int str_first_char_occurence(const char *str, const char *c) -{ - if (!str) - return -1; - - int i = 0; - while (c[str_find(c, str[i])] == '\0' && str[i] != '\0') - ++i; - return i; -} - -int str_count(const char *str, char c) -{ - if (!str) - return -1; - - int count = 0; - while (*str != '\0') - count += (*(str++) == c); - return count; -} diff --git a/iz1/src/attr.c b/iz1/src/attr.c deleted file mode 100644 index c2a9cf9..0000000 --- a/iz1/src/attr.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "html_tag/attr.h" - -#include - -#include "my_str/mem.h" -#include "my_str/alg.h" - -bool check_attr_format(const char *str, size_t *attr_end) -{ - if (!str || !attr_end) - return false; - - size_t eq_pos = str_find(str, '='); - if (str[eq_pos] == '\0') - return false; - - for (int i = 0; i < eq_pos; ++i) - { - if (str[i] == ' ') - return false; - } - - eq_pos++; - if (str[eq_pos] == '\"') - *attr_end = str_find(str + eq_pos + 1, '\"') + 2; - else - *attr_end = str_first_char_occurence(str + eq_pos, " >"); - - *attr_end += eq_pos; - return str[*attr_end] != '\0'; -} - -void free_attr(tag_attr_t **attr) -{ - free((*attr)->name); - free((*attr)->value); - free(*attr); - *attr = NULL; -} - -tag_attr_t *parse_attr(const char *str, int *attr_end) -{ - const char *str_start = str; - tag_attr_t *attr = (tag_attr_t *) malloc(sizeof(tag_attr_t)); - - str += str_create_word(&attr->name, str, "="); - if (*str == '"') - str += str_create_word(&attr->value, str + 1, "\"") + 2; - else - str += str_create_word(&attr->value, str, " >"); - - ptrdiff_t attr_end_ = str - str_start; - *attr_end = (int) (attr_end_); - - return attr; -} - -tag_attr_t **parse_attr_arr(const char *str, size_t count) -{ - tag_attr_t **attr_arr = (tag_attr_t **) malloc(count * sizeof(tag_attr_t *)); - for (size_t i = 0; i < count; ++i) - { - int attr_end = 0; - attr_arr[i] = parse_attr(str, &attr_end); - str += attr_end; - } - return attr_arr; -} diff --git a/iz1/src/html_tag.c b/iz1/src/html_tag.c deleted file mode 100644 index bf4ba45..0000000 --- a/iz1/src/html_tag.c +++ /dev/null @@ -1,87 +0,0 @@ -#include "html_tag/html_tag.h" - -#include "my_str/mem.h" -#include "my_str/alg.h" - -bool check_html_tag_format(const char *str) -{ - bool ok = str && str[0] == '<'; - if (ok && str[1] == '/') - { - size_t closing_pos = str_find(str, '>'); - for (size_t i = 2; ok && i < closing_pos; ++i) - ok = (ASCII_NAME_ALLOWED[str_find(ASCII_NAME_ALLOWED, str[i])] != '\0'); - } else if (ok) - { - size_t name_end = str_first_char_occurence(str, " >"); - for (size_t i = 1; ok && i < name_end; ++i) - ok = (ASCII_NAME_ALLOWED[str_find(ASCII_NAME_ALLOWED, str[i])] != '\0'); - - if (ok) - { - size_t closing_pos = str_find(str, '>'); - ok = (str[closing_pos] == '>'); - } - - if (ok) - { - size_t attr_end = name_end; - str += attr_end; - while (ok && str[0] != '>') - { - ok = check_attr_format(str + 1, &attr_end); - str += attr_end + 1; - } - } - } - return ok; -} - -html_tag *parse_tag(const char *str) -{ - if (!check_html_tag_format(str)) - return NULL; - - html_tag *tag = (html_tag *) malloc(sizeof(html_tag)); - - if (tag == NULL) - return NULL; - - str += parse_status(str, tag); - tag->attributes_count = str_count(str, '='); - - if (!tag->is_opening || tag->attributes_count == 0) - str += str_create_word(&tag->name, str, ">"); - else - str += str_create_word(&tag->name, str, " "); - - tag->attributes = parse_attr_arr(str, tag->attributes_count); - - return tag; -} - -size_t parse_status(const char *str, html_tag *tag) -{ - int i = 0; - if (str[i] == '<') - { - ++i; - if (str[i] == '/') - { - tag->is_opening = false; - ++i; - } else - tag->is_opening = true; - } - return i; -} - -void free_tag(html_tag **tag) -{ - free((*tag)->name); - for (size_t i = 0; i < (*tag)->attributes_count; ++i) - free_attr((*tag)->attributes + i); - free((*tag)->attributes); - free(*tag); - *tag = NULL; -} diff --git a/iz1/src/main.c b/iz1/src/main.c deleted file mode 100644 index 96ceb78..0000000 --- a/iz1/src/main.c +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» - * и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на - * вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. - */ -#include - -#include "html_tag/html_tag.h" - -#define MAX_STR_LEN 256 - -int main() -{ - char str[MAX_STR_LEN]; - fgets(str, sizeof(str), stdin); - html_tag *tag = parse_tag(str); - if (!tag) - puts("Wrong tag format!"); - else - { - printf("Tag name = \"%s\"\n", tag->name); - if (tag->is_opening) - puts("Opening tag"); - else - puts("Closing tag"); - if (tag->attributes_count) - { - puts("Attributes:"); - for (size_t i = 0; i < tag->attributes_count; ++i) - printf("%s=\"%s\"\n", tag->attributes[i]->name, tag->attributes[i]->value); - } - free_tag(&tag); - } - return 0; -} \ No newline at end of file diff --git a/iz1/src/mem.c b/iz1/src/mem.c deleted file mode 100644 index c90fa97..0000000 --- a/iz1/src/mem.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "my_str/mem.h" - -#include "my_str/alg.h" - - -size_t str_create_ncopy(char **to_allocate, const char *to_copy, size_t n) -{ - if (!to_copy || !to_allocate) - return 0; - - size_t to_copy_len = strlen(to_copy); - size_t allocate_size = (to_copy_len > n ? n : to_copy_len) + 1; - *to_allocate = (char *) malloc(allocate_size); - int i; - for (i = 0; i < n && to_copy[i] != '\0'; ++i) - (*to_allocate)[i] = to_copy[i]; - - (*to_allocate)[i] = '\0'; - - return allocate_size; -} - -size_t str_create_word(char **to_allocate, const char *src, const char *sep) -{ - if (!src || !to_allocate) - return 0; - - int word_end = str_first_char_occurence(src, sep); - return str_create_ncopy(to_allocate, src, word_end); -} diff --git a/iz1/test/CMakeLists.txt b/iz1/test/CMakeLists.txt deleted file mode 100644 index 50c75f3..0000000 --- a/iz1/test/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -include_directories("${PROJECT_SOURCE_DIR}/include") - -file(GLOB sources "${PROJECT_SOURCE_DIR}/src/*.c") -list(REMOVE_ITEM sources "${PROJECT_SOURCE_DIR}/src/main.c") - -file(GLOB tests "${PROJECT_SOURCE_DIR}/test/*.cpp") -list(REMOVE_ITEM tests "${PROJECT_SOURCE_DIR}/test/main.cpp") - -if (ENABLE_GCOV) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs") -endif () - - -foreach (file ${tests}) - set(name) - get_filename_component(name ${file} NAME_WE) - add_executable("${name}_tests" - ${sources} - ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp") - target_link_libraries("${name}_tests" gtest_main) - add_test(NAME ${name} COMMAND "${name}_tests") -endforeach () \ No newline at end of file diff --git a/iz1/test/attr.cpp b/iz1/test/attr.cpp deleted file mode 100644 index d3d0a4f..0000000 --- a/iz1/test/attr.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "gtest/gtest.h" -#include - -extern "C" { -#include "html_tag/attr.h" -} - -TEST(correct_input, no_quotes) -{ - char correct_name[] = "attr1"; - char correct_value[] = "value1"; - char line[] = "attr1=value1"; - int attr_end = 0; - tag_attr_t *attr = parse_attr(line, &attr_end); - ASSERT_EQ(strcmp(attr->name, correct_name), 0); - ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(&attr); -} - -TEST(correct_input, quotes_one) -{ - char correct_name[] = "attr1"; - char correct_value[] = "value1"; - char line[] = "attr1=\"value1\""; - int attr_end = 0; - tag_attr_t *attr = parse_attr(line, &attr_end); - ASSERT_EQ(strcmp(attr->name, correct_name), 0); - ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(&attr); -} - -TEST(correct_input, quotes_two) -{ - char correct_name[] = "attr1"; - char correct_value[] = "value1 value2"; - char line[] = "attr1=\"value1 value2\""; - int attr_end = 0; - tag_attr_t *attr = parse_attr(line, &attr_end); - ASSERT_EQ(strcmp(attr->name, correct_name), 0); - ASSERT_EQ(strcmp(attr->value, correct_value), 0); - free_attr(&attr); -} diff --git a/iz1/test/check_attr_format.cpp b/iz1/test/check_attr_format.cpp deleted file mode 100644 index b5d2e83..0000000 --- a/iz1/test/check_attr_format.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "gtest/gtest.h" -#include - -extern "C" { -#include "html_tag/attr.h" -} - -TEST(format_checker_correct, test1) -{ - char str[] = "attr1=value1 "; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - -TEST(format_checker_correct, test2) -{ - char str[] = "attr1=\"value1\" "; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - -TEST(format_checker_correct, test3) -{ - char str[] = "attr1=\"value1 value2\" "; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - - -TEST(format_checker_correct, test1_last) -{ - char str[] = "attr1=value1>"; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - -TEST(format_checker_correct, test2_last) -{ - char str[] = "attr1=\"value1\">"; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - -TEST(format_checker_correct, test3_last) -{ - char str[] = "attr1=\"value1 value2\">"; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), true); -} - -TEST(format_checker_incorrect, random_word) -{ - char str[] = "random_word"; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), false); -} - -TEST(format_checker_incorrect, space_before_eq) -{ - char str[] = "word attr=val"; - size_t attr_end; - ASSERT_EQ(check_attr_format(str, &attr_end), false); -} diff --git a/iz1/test/check_html_tag_format.cpp b/iz1/test/check_html_tag_format.cpp deleted file mode 100644 index a505351..0000000 --- a/iz1/test/check_html_tag_format.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include "gtest/gtest.h" -#include - -extern "C" { -#include "html_tag/html_tag.h" -} - -TEST(tag_format_check_correct, simple_opening) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, simple_closing) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_one_attr) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_two_attr) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_two_quoted_attr) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_two_quoted_attr_r) -{ - char str[] = ""; - ASSERT_EQ(check_html_tag_format(str), true); -} - - -TEST(tag_format_check_correct, opening_two_quoted_attr_) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_three_quoted_attr) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_correct, opening_three_quoted_attr_) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), true); -} - -TEST(tag_format_check_incorrect, no_name) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), false); -} - -TEST(tag_format_check_incorrect, closing_tag_attrs) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), false); -} - -TEST(tag_format_check_incorrect, random_symbols) -{ - char str[] = R"(lskdjfo isdfo)"; - ASSERT_EQ(check_html_tag_format(str), false); -} - -TEST(tag_format_check_incorrect, random_things_inside_tag) -{ - char str[] = R"()"; - ASSERT_EQ(check_html_tag_format(str), false); -} - - - - - - - - diff --git a/iz1/test/html_tag.cpp b/iz1/test/html_tag.cpp deleted file mode 100644 index c71fe47..0000000 --- a/iz1/test/html_tag.cpp +++ /dev/null @@ -1,127 +0,0 @@ -#include "gtest/gtest.h" -#include - -extern "C" { -#include "html_tag/html_tag.h" -} - -TEST(tag_correct_input, no_quotes) -{ - char src[] = ""; - char expected_name[] = "opening_tag"; - bool expected_opening = true; - size_t expected_attr_count = 1; - char expected_attr_names[][10] = {"attr1"}; - char expected_attr_values[][10] = {"value1"}; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - for (size_t i = 0; i < res->attributes_count; ++i) - { - ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); - ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); - } - free_tag(&res); -} - -TEST(tag_correct_input, quotes_one) -{ - char src[] = ""; - char expected_name[] = "opening_tag"; - bool expected_opening = true; - size_t expected_attr_count = 1; - char expected_attr_names[][10] = {"attr1"}; - char expected_attr_values[][10] = {"value1"}; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - for (size_t i = 0; i < res->attributes_count; ++i) - { - ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); - ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); - } - free_tag(&res); -} - -TEST(tag_correct_input, quotes_two) -{ - char src[] = ""; - char expected_name[] = "opening_tag"; - bool expected_opening = true; - size_t expected_attr_count = 1; - char expected_attr_names[][20] = {"attr1"}; - char expected_attr_values[][20] = {"value1 value2"}; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - for (size_t i = 0; i < res->attributes_count; ++i) - { - ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); - ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); - } - free_tag(&res); -} - - -TEST(tag_correct_input, two_attrs) -{ - char src[] = ""; - char expected_name[] = "opening_tag"; - bool expected_opening = true; - size_t expected_attr_count = 2; - char expected_attr_names[][20] = {"attr1", "attr2"}; - char expected_attr_values[][20] = {"value1 value2", "value3"}; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - for (size_t i = 0; i < res->attributes_count; ++i) - { - ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); - ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); - } - free_tag(&res); -} - -TEST(tag_correct_input, three_attrs) -{ - char src[] = R"()"; - char expected_name[] = "opening_tag"; - bool expected_opening = true; - size_t expected_attr_count = 3; - char expected_attr_names[][20] = {"attr1", "attr2", "attr3"}; - char expected_attr_values[][20] = {"value1 value2", "value3", "value4"}; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - for (size_t i = 0; i < res->attributes_count; ++i) - { - ASSERT_EQ(strcmp(res->attributes[i]->name, expected_attr_names[i]), 0); - ASSERT_EQ(strcmp(res->attributes[i]->value, expected_attr_values[i]), 0); - } - free_tag(&res); -} - - -TEST(tag_correct_input, closing) -{ - char src[] = ""; - char expected_name[] = "closing_tag"; - bool expected_opening = false; - size_t expected_attr_count = 0; - - html_tag *res = parse_tag(src); - ASSERT_EQ(strcmp(res->name, expected_name), 0); - ASSERT_EQ(res->is_opening, expected_opening); - ASSERT_EQ(res->attributes_count, expected_attr_count); - free_tag(&res); -} diff --git a/iz1/test/main.cpp b/iz1/test/main.cpp deleted file mode 100644 index b42b721..0000000 --- a/iz1/test/main.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include "gtest/gtest.h" - -int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} \ No newline at end of file From 12f4198ce7d80bcca96bad92218c6c782185cf21 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 10:24:09 +0300 Subject: [PATCH 61/65] updated travis --- .travis.yml | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 656b5a4..f118c8c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,22 +36,3 @@ jobs: - cmake -DENABLE_CPPCHECK=ON .. - make - make check - - # - # Coverage - # - # - os: linux - # env: - # - TEST="GCovr" - # addons: - # apt: - # packages: - # - gcov - # before_script: - # - pip3 install gcovr - # script: - # - cmake -DENABLE_GCOV - # - make - # - ctest - # - cd .. && gcovr - From 204e2ff46ca1542d3f03fa77d0d29ecbcd16ccf4 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 11:16:40 +0300 Subject: [PATCH 62/65] updated profiling --- iz2/CMakeLists.txt | 3 +++ iz2/include/moodfinder_errors.h | 3 +++ iz2/include/moodfinder_profile.h | 4 ++++ iz2/src/main.c | 5 +++++ iz2/src/moodfinder_profiler.c | 0 iz2/src/moodfinder_s.c | 9 +++++++-- iz2/test/CMakeLists.txt | 8 ++++++-- iz2/test/moodfinder.cpp | 15 +++++++++++---- 8 files changed, 39 insertions(+), 8 deletions(-) create mode 100644 iz2/include/moodfinder_errors.h create mode 100644 iz2/include/moodfinder_profile.h create mode 100644 iz2/src/moodfinder_profiler.c diff --git a/iz2/CMakeLists.txt b/iz2/CMakeLists.txt index 733be47..94c813d 100755 --- a/iz2/CMakeLists.txt +++ b/iz2/CMakeLists.txt @@ -26,6 +26,7 @@ endif () set(libmoodfinder_s_sources ${PROJECT_SOURCE_DIR}/include/moodfinder.h + ${PROJECT_SOURCE_DIR}/include/moodfinder_errors.h ${PROJECT_SOURCE_DIR}/src/moodfinder_s.c ) @@ -36,6 +37,8 @@ add_library(libmoodfinder_s STATIC ${libmoodfinder_s_sources}) set(main_sources ${PROJECT_SOURCE_DIR}/src/main.c + ${PROJECT_SOURCE_DIR}/src/moodfinder_profiler.c + ${PROJECT_SOURCE_DIR}/include/moodfinder_profile.h ) add_executable(main ${main_sources}) diff --git a/iz2/include/moodfinder_errors.h b/iz2/include/moodfinder_errors.h new file mode 100644 index 0000000..cedd780 --- /dev/null +++ b/iz2/include/moodfinder_errors.h @@ -0,0 +1,3 @@ +#define EMPTY_FILE_ERROR -2 +#define FILE_NOT_EXIST_ERROR -1 +#define MMAP_FAILED -3 \ No newline at end of file diff --git a/iz2/include/moodfinder_profile.h b/iz2/include/moodfinder_profile.h new file mode 100644 index 0000000..fc5ef41 --- /dev/null +++ b/iz2/include/moodfinder_profile.h @@ -0,0 +1,4 @@ +#ifndef IZ1_MOODFINDER_PROFILE_H +#define IZ1_MOODFINDER_PROFILE_H + +#endif //IZ1_MOODFINDER_PROFILE_H diff --git a/iz2/src/main.c b/iz2/src/main.c index 4023a5f..3813fb7 100644 --- a/iz2/src/main.c +++ b/iz2/src/main.c @@ -10,10 +10,15 @@ #include #include +void construct_file(const char *path, int status, int size); + + + int main(int argc, char *argv[]) { struct timespec start, finish; double elapsed; + clock_gettime(CLOCK_MONOTONIC, &start); int mood = find_mood(argv[1]); clock_gettime(CLOCK_MONOTONIC, &finish); diff --git a/iz2/src/moodfinder_profiler.c b/iz2/src/moodfinder_profiler.c new file mode 100644 index 0000000..e69de29 diff --git a/iz2/src/moodfinder_s.c b/iz2/src/moodfinder_s.c index f5b6127..f1f4e9c 100644 --- a/iz2/src/moodfinder_s.c +++ b/iz2/src/moodfinder_s.c @@ -1,7 +1,7 @@ #include "moodfinder.h" +#include "moodfinder_errors.h" #include -#include #include #include #include @@ -22,7 +22,11 @@ int find_mood(const char *filename) if (region == MAP_FAILED) { close(fd); - return -1; + if (file_size == 0) + return EMPTY_FILE_ERROR; + if (fd == -1) + return FILE_NOT_EXIST_ERROR; + return MMAP_FAILED; } long long mood = 0; for (size_t i = 0; i < file_size - 1; ++i) @@ -30,6 +34,7 @@ int find_mood(const char *filename) if (region[i] == ':') mood += (region[i + 1] == ')') + -1 * (region[i + 1] == '('); } + munmap(region, file_size); close(fd); return mood > 0 ? POSITIVE : (mood == 0 ? NEUTRAL : NEGATIVE); } \ No newline at end of file diff --git a/iz2/test/CMakeLists.txt b/iz2/test/CMakeLists.txt index 16de5cc..79092f5 100755 --- a/iz2/test/CMakeLists.txt +++ b/iz2/test/CMakeLists.txt @@ -13,10 +13,14 @@ foreach (file ${tests}) get_filename_component(name ${file} NAME_WE) add_executable("${name}_tests" ${file} - "${PROJECT_SOURCE_DIR}/test/main.cpp") + "${PROJECT_SOURCE_DIR}/test/main.cpp" + ) target_link_libraries("${name}_tests" libmoodfinder_s gtest_main ) - add_test(NAME ${name} COMMAND "${name}_tests") + add_test(NAME ${name} + COMMAND "${name}_tests" + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) endforeach () \ No newline at end of file diff --git a/iz2/test/moodfinder.cpp b/iz2/test/moodfinder.cpp index 05e7180..8009016 100644 --- a/iz2/test/moodfinder.cpp +++ b/iz2/test/moodfinder.cpp @@ -1,18 +1,18 @@ #include "gtest/gtest.h" #include -#include using namespace std; string construct_path(const string &filename) { - const static string examples = "./examples/"; + const static string examples = "examples/"; return examples + filename; } extern "C" { #include "moodfinder.h" +#include "moodfinder_errors.h" } TEST(find_mood_positive, clear) @@ -48,5 +48,12 @@ TEST(find_mood_neutral, dirty) TEST(find_mood_errors, empty) { const string filename = "empty.txt"; - ASSERT_EQ(find_mood(construct_path(filename).c_str()), -1); -} \ No newline at end of file + ASSERT_EQ(find_mood(construct_path(filename).c_str()), EMPTY_FILE_ERROR); +} + +TEST(find_mood_errors, not_exitsing) +{ + const string s = construct_path("not_existing.txt"); + static const char *filename = s.c_str(); + ASSERT_EQ(find_mood(filename), FILE_NOT_EXIST_ERROR); +} From 3f2650a4437798ab05c844ed5c277534113fc5d4 Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 12:02:44 +0300 Subject: [PATCH 63/65] corrected memory error --- iz2/README.MD | 45 +++++++++++++++----------- iz2/include/moodfinder_profile.h | 6 ++++ iz2/src/main.c | 23 ++------------ iz2/src/moodfinder_profiler.c | 54 ++++++++++++++++++++++++++++++++ iz2/src/moodfinder_s.c | 4 +-- 5 files changed, 92 insertions(+), 40 deletions(-) diff --git a/iz2/README.MD b/iz2/README.MD index 0b68772..48f66e4 100755 --- a/iz2/README.MD +++ b/iz2/README.MD @@ -1,20 +1,29 @@ -# Индивидуальное задание 1 - -ИЗ1 посвящено приобретению навыков безопасной работы с памятью на языке C с использованием базовых структур данных и налаживания базовой инфраструктуры для автоматической проверки кода. В качестве результата ИЗ2 ожидается: -* грамотное разбиение проекта на файлы; -* использование безопасного стиля программирования - проверка возможных ошибок, корректное завершение программы в случае их возникновения и правильная работа с памятью; -* максимальное покрытие кода юнит-тестами; -* рабочий CI, включающего в себя автоматическую сборку проекта, статический анализ кода, прохождение линтеров, valgrind, запуск юнит-тестов и получение отчёта о покрытии кода тестами -* все автоматические проверки должны проходить на итоговой версии, которая проходит ревью Вариант #23 -Создать структуру для хранения информации об HTML-теге: его имени, признаке «открывающий/закрывающий» и атрибутах тега. Составить с ее использованием программу, включающую в себя функцию, принимающую на вход текстовую строку с одним тегом. На выход функция должна возвращать указатель на инициализированную структуру. +Сравните и выведите в консоль время работы последовательного и параллельного с использованием нескольких процессов +алгоритмов, каждый из которых выделяет в динамической памяти символьный массив размером 100 Мб и, +рассматривая его содержимое как абстрактную переписку, определяет эмоциональную окраску последней. Переписка считается +оптимистичной, если диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. -Требования к оформлению: -Программа должна быть реализована на языке C и работать для произвольных наборов входных данных (в том числе и ошибочных), вводимых пользователем с клавиатуры. Должна быть выполнена грамотная декомпозиция на функции и файлы. -Помимо самой программы необходимо: -– разработать набор юнит-тестов, проверяющих корректную работу реализованных функций. Обеспечить максимальное покрытие исходного кода тестами; -– оформить задачу в виде Merge Request отдельной ветки в основную ветку проекта. -Внимание: в основной ветке проекта никакого кода быть не должно! -– развернуть CI, в рамках которого автоматизировать сборку проекта, прохождение юнит-тестов под valgrind, генерацию отчёта о покрытии кода тестами, линтера и статического анализатора исходного кода; -– после прохождения всех проверок необходимо отправить код на ревью своему преподавателю; -– ревью - процесс итерационный. До наступления дедлайна можно проходить несколько итераций, улучшая свою оценку. Решения после дедлайна не принимаются; +Результаты замеров +``` +100000 chars : 0.000568 seconds +600000 chars : 0.003453 seconds +1100000 chars : 0.005946 seconds +1600000 chars : 0.008527 seconds +2100000 chars : 0.011032 seconds +2600000 chars : 0.013986 seconds +3100000 chars : 0.016421 seconds +3600000 chars : 0.018687 seconds +4100000 chars : 0.021882 seconds +4600000 chars : 0.023492 seconds +5100000 chars : 0.026175 seconds +5600000 chars : 0.029254 seconds +6100000 chars : 0.031903 seconds +6600000 chars : 0.034180 seconds +7100000 chars : 0.036982 seconds +7600000 chars : 0.039288 seconds +8100000 chars : 0.042387 seconds +8600000 chars : 0.045159 seconds +9100000 chars : 0.048569 seconds +9600000 chars : 0.050803 seconds +``` diff --git a/iz2/include/moodfinder_profile.h b/iz2/include/moodfinder_profile.h index fc5ef41..d5656fe 100644 --- a/iz2/include/moodfinder_profile.h +++ b/iz2/include/moodfinder_profile.h @@ -1,4 +1,10 @@ #ifndef IZ1_MOODFINDER_PROFILE_H #define IZ1_MOODFINDER_PROFILE_H +void generate_file(const char *filename, int status, int size); + +double profile_on_file(const char *filename, int count); + +void profile_app(int start_size, int end_size, int step); + #endif //IZ1_MOODFINDER_PROFILE_H diff --git a/iz2/src/main.c b/iz2/src/main.c index 3813fb7..9c2bd1c 100644 --- a/iz2/src/main.c +++ b/iz2/src/main.c @@ -5,27 +5,10 @@ эмоциональную окраску последней. Переписка считается оптимистичной, если диграфов :) в ней больше, чем диграфов :(; в противном случае переписка признается пессимистичной. */ +#include -#include "moodfinder.h" -#include -#include - -void construct_file(const char *path, int status, int size); - - - -int main(int argc, char *argv[]) +int main() { - struct timespec start, finish; - double elapsed; - - clock_gettime(CLOCK_MONOTONIC, &start); - int mood = find_mood(argv[1]); - clock_gettime(CLOCK_MONOTONIC, &finish); - if (mood != -1) - printf("Mood: %d\n", mood); - elapsed = (double)(finish.tv_sec - start.tv_sec); - elapsed += (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; - printf("Work time: %lf\n", elapsed); + profile_app(100000, 10000000, 500000); return 0; } diff --git a/iz2/src/moodfinder_profiler.c b/iz2/src/moodfinder_profiler.c index e69de29..e036c20 100644 --- a/iz2/src/moodfinder_profiler.c +++ b/iz2/src/moodfinder_profiler.c @@ -0,0 +1,54 @@ +#include "moodfinder_profile.h" + +#include "moodfinder.h" +#include "moodfinder_errors.h" + +#include +#include + +void generate_file(const char *filename, int status, int size) +{ + FILE *f = fopen(filename, "w"); + if (!f) + return; + char c = (char)(status == NEGATIVE ? '(' : ')'); + if (status == NEUTRAL) + { + size /= 2; + for (int i = 0; i < size; ++i) + fputs(":(", f); + } + for (int i = 0; i < size; ++i) + fprintf(f, ":%c", c); + fclose(f); +} + + +double profile_on_file(const char *filename, int count) +{ + struct timespec start, finish; + double elapsed; + double mean_time = 0; + + for (int i = 0; i < count; ++i) + { + clock_gettime(CLOCK_MONOTONIC, &start); + int mood = find_mood(filename); + clock_gettime(CLOCK_MONOTONIC, &finish); + elapsed = (double) (finish.tv_sec - start.tv_sec) + (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; + mean_time += elapsed / (double)count; + } + return mean_time; +} + +void profile_app(int start_size, int end_size, int step) +{ + const char filename[] = "f.txt"; + for (int size = start_size; size <= end_size; size += step) + { + generate_file(filename, NEUTRAL, size); + double res = profile_on_file(filename, 10); + printf("%d chars : %lf seconds\n", size, res); + } +} + diff --git a/iz2/src/moodfinder_s.c b/iz2/src/moodfinder_s.c index f1f4e9c..7f8cca8 100644 --- a/iz2/src/moodfinder_s.c +++ b/iz2/src/moodfinder_s.c @@ -10,6 +10,8 @@ int find_mood(const char *filename) { int fd = open(filename, O_RDONLY); + if (fd == -1) + return FILE_NOT_EXIST_ERROR; struct stat st; stat(filename, &st); size_t file_size = st.st_size; @@ -24,8 +26,6 @@ int find_mood(const char *filename) close(fd); if (file_size == 0) return EMPTY_FILE_ERROR; - if (fd == -1) - return FILE_NOT_EXIST_ERROR; return MMAP_FAILED; } long long mood = 0; From 38a41df79bb44dba6960ae20157fac4ccf7fd7cf Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 13:12:50 +0300 Subject: [PATCH 64/65] corrected cppcheck --- iz2/src/moodfinder_profiler.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/iz2/src/moodfinder_profiler.c b/iz2/src/moodfinder_profiler.c index e036c20..09e8062 100644 --- a/iz2/src/moodfinder_profiler.c +++ b/iz2/src/moodfinder_profiler.c @@ -27,7 +27,6 @@ void generate_file(const char *filename, int status, int size) double profile_on_file(const char *filename, int count) { struct timespec start, finish; - double elapsed; double mean_time = 0; for (int i = 0; i < count; ++i) @@ -35,7 +34,7 @@ double profile_on_file(const char *filename, int count) clock_gettime(CLOCK_MONOTONIC, &start); int mood = find_mood(filename); clock_gettime(CLOCK_MONOTONIC, &finish); - elapsed = (double) (finish.tv_sec - start.tv_sec) + (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; + double elapsed = (double) (finish.tv_sec - start.tv_sec) + (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; mean_time += elapsed / (double)count; } return mean_time; From 9320a692325ff9f39a11180e088079014ff6028a Mon Sep 17 00:00:00 2001 From: Paul Date: Thu, 29 Oct 2020 13:38:32 +0300 Subject: [PATCH 65/65] corrected cppcheck --- iz2/src/moodfinder_profiler.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/iz2/src/moodfinder_profiler.c b/iz2/src/moodfinder_profiler.c index 09e8062..754b4f9 100644 --- a/iz2/src/moodfinder_profiler.c +++ b/iz2/src/moodfinder_profiler.c @@ -32,7 +32,7 @@ double profile_on_file(const char *filename, int count) for (int i = 0; i < count; ++i) { clock_gettime(CLOCK_MONOTONIC, &start); - int mood = find_mood(filename); + find_mood(filename); clock_gettime(CLOCK_MONOTONIC, &finish); double elapsed = (double) (finish.tv_sec - start.tv_sec) + (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0; mean_time += elapsed / (double)count;