├── .github └── FUNDING.yml ├── test ├── Makefile ├── test_stack_1.c ├── test_queue_1.c ├── test_bst_1.c ├── test_avl_1.c ├── test_dlist_1.c └── avl_Thread_Safe_Test.c ├── CMakeLists.txt ├── Makefile ├── include ├── log.h ├── stack.h ├── queue.h ├── dlist.h ├── tree.h ├── common.h └── avl.h ├── src ├── log.c ├── stack.c ├── queue.c ├── common.c ├── dlist.c ├── tree.c └── avl.c ├── apilist.txt ├── README.md └── LICENSE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: jarun 4 | -------------------------------------------------------------------------------- /test/Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -Wall -Wextra -g -fsanitize=address,undefined $(INCLUDE) 3 | 4 | #INCLUDE = -I/usr/include/dslib 5 | #LIBS = -lds 6 | #SRCDIR = 7 | 8 | INCLUDE = -I../include 9 | LIBS = 10 | SRCDIR = ../src/*.c 11 | 12 | all: 13 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_avl_1 test_avl_1.c $(LIBS) 14 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_bst_1 test_bst_1.c $(LIBS) 15 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_dlist_1 test_dlist_1.c $(LIBS) 16 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_queue_1 test_queue_1.c $(LIBS) 17 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_stack_1 test_stack_1.c $(LIBS) 18 | $(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o avl_Thread_Safe_Test avl_Thread_Safe_Test.c $(LIBS) -lpthread 19 | 20 | .PHONY: clean 21 | clean: 22 | rm -f test_avl_1 test_bst_1 test_dlist_1 test_queue_1 test_stack_1 avl_Thread_Safe_Test 23 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(CMAKE_POSITION_INDEPENDENT_CODE ON) 2 | 3 | cmake_minimum_required(VERSION 3.12) 4 | 5 | project(dslib) 6 | 7 | file(GLOB files CONFIGURE_DEPENDS include/*.h src/*.c) 8 | add_library(ds SHARED ${files}) 9 | 10 | find_package(Threads REQUIRED) 11 | target_link_libraries(ds PUBLIC Threads::Threads) 12 | 13 | target_include_directories(ds 14 | PUBLIC 15 | $ 16 | $ 17 | ) 18 | 19 | if (UNIX) 20 | target_link_libraries(ds PRIVATE -Wl,-undefined,dynamic_lookup) 21 | endif() 22 | 23 | file(GLOB files CONFIGURE_DEPENDS test/*.c ) 24 | foreach(file IN LISTS files) 25 | get_filename_component(test_name ${file} NAME_WE) 26 | 27 | add_executable(${test_name} ${file}) 28 | target_link_libraries(${test_name} PRIVATE ds) 29 | 30 | add_test(${test_name} ${test_name}) 31 | endforeach() 32 | 33 | include(CTest) 34 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC = gcc 2 | CFLAGS = -Wall -Wextra -Werror -O3 -fPIC $(INCLUDE) 3 | 4 | SRC = $(wildcard src/*.c) 5 | OBJS = $(SRC:%.c=%.o) 6 | INCLUDE = -Iinclude 7 | TARGET = libds.so.1.0 8 | 9 | BINDIR = ./bin 10 | HEADERDIR = /usr/include/dslib 11 | DESTDIR = /usr/lib 12 | 13 | all: $(TARGET) 14 | 15 | $(TARGET): $(OBJS) 16 | mkdir -p $(BINDIR) 17 | $(CC) $(CFLAGS) -shared -Wl,-soname,libds.so.1 -o $(BINDIR)/$(TARGET) $(OBJS) 18 | strip $(BINDIR)/$(TARGET) 19 | 20 | .PHONY: test clean 21 | test: 22 | cd test && $(MAKE) 23 | 24 | clean: 25 | rm -f $(OBJS) $(BINDIR)/$(TARGET) 26 | rm -rf $(BINDIR) 27 | # clean test files too 28 | cd test && $(MAKE) clean 29 | 30 | distclean: clean 31 | rm -f *~ 32 | 33 | install: $(TARGET) 34 | install -m755 -d $(HEADERDIR) 35 | install -m644 -t $(HEADERDIR) include/*.h 36 | install -o root -m 644 $(BINDIR)/$(TARGET) $(DESTDIR)/ 37 | ln -sf $(DESTDIR)/$(TARGET) $(DESTDIR)/libds.so.1 38 | ln -sf $(DESTDIR)/libds.so.1 $(DESTDIR)/libds.so 39 | 40 | uninstall: 41 | rm -rf $(HEADERDIR) 42 | rm -f $(DESTDIR)/libds.so $(DESTDIR)/libds.so.1 $(DESTDIR)/$(TARGET) 43 | -------------------------------------------------------------------------------- /include/log.h: -------------------------------------------------------------------------------- 1 | /* 2 | * A modular, level based log file implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2014 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #pragma once 22 | 23 | #include 24 | #include 25 | 26 | #define ERROR 0 27 | #define INFO 1 28 | #define DEBUG 2 29 | 30 | #define log(level, format, ...) \ 31 | debug_log(__FILE__, __func__, __LINE__, \ 32 | level, format, ##__VA_ARGS__) 33 | 34 | void debug_log(const char *file, 35 | const char *func, 36 | int line, 37 | int level, 38 | const char *format, 39 | ...) __attribute__((__format__(printf, 5, 6))); 40 | -------------------------------------------------------------------------------- /include/stack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Stack abstraction 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "dlist.h" 22 | 23 | #pragma once 24 | 25 | /* Stack ADT using a circular doubly linked list */ 26 | typedef struct { 27 | dlist_pp head; 28 | } stack_t, *stack_p; 29 | 30 | /* Create a new Stack */ 31 | stack_p get_stack(void); 32 | 33 | /* Push a value to Stack */ 34 | bool push(stack_p stack, void *val); 35 | 36 | /* Pop a value from Stack */ 37 | void *pop(stack_p stack); 38 | 39 | /* Check if a stack is empty */ 40 | bool isStackEmpty(stack_p stack); 41 | 42 | /* Clean up Stack */ 43 | bool destroy_stack(stack_p stack); 44 | -------------------------------------------------------------------------------- /include/queue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Queue abstraction 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "dlist.h" 22 | 23 | #pragma once 24 | 25 | /* Queue ADT using a circular doubly linked list */ 26 | typedef struct { 27 | dlist_pp head; 28 | } queue_t, *queue_p; 29 | 30 | /* Create a new Queue */ 31 | queue_p get_queue(void); 32 | 33 | /* Add a value to Queue */ 34 | bool enqueue(queue_p queue, void *val); 35 | 36 | /* Remove a value from Queue */ 37 | void *dequeue(queue_p queue); 38 | 39 | /* Check if the Queue is empty */ 40 | bool isQueueEmpty(queue_p queue); 41 | 42 | /* Clean up Queue */ 43 | bool destroy_queue(queue_p queue); 44 | -------------------------------------------------------------------------------- /src/log.c: -------------------------------------------------------------------------------- 1 | /* 2 | * A modular, level based log file implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2014 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "log.h" 22 | 23 | extern int current_log_level; 24 | char *logarr[] = {"ERROR", "INFO", "DEBUG"}; 25 | 26 | void debug_log(const char *file, 27 | const char *func, 28 | int line, 29 | int level, 30 | const char *format, 31 | ...) 32 | { 33 | va_list ap; 34 | 35 | va_start(ap, format); 36 | 37 | if (level < 0 || level > DEBUG) 38 | return; 39 | 40 | if (level <= current_log_level) { 41 | fprintf(stderr, "[%s, %s(), ln %d] %s: ", 42 | file, func, line, logarr[level]); 43 | vfprintf(stderr, format, ap); 44 | } 45 | 46 | va_end(ap); 47 | } 48 | -------------------------------------------------------------------------------- /test/test_stack_1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for stack 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | int current_log_level = DEBUG; 25 | 26 | /* Test stack */ 27 | int main(void) 28 | { 29 | int count = 5; 30 | int arr[5] = {0, 1, 2, 3, 4}; 31 | int *val; 32 | 33 | stack_p stack = get_stack(); 34 | 35 | while (count) { 36 | if (push(stack, &arr[--count]) == FALSE) { 37 | log(ERROR, "push failed!\n"); 38 | destroy_stack(stack); 39 | return -1; 40 | } 41 | 42 | log(DEBUG, "pushed: arr[%d] = %d\n", count, arr[count]); 43 | } 44 | 45 | count = 5; 46 | 47 | while (count) { 48 | val = pop(stack); 49 | if (val) 50 | log(DEBUG, "popped: arr[%d] = %d\n", --count, (int)*val); 51 | else 52 | log(ERROR, "pop failed!\n"); 53 | } 54 | 55 | destroy_stack(stack); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /test/test_queue_1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for queue 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | int current_log_level = DEBUG; 25 | 26 | /* Test queue */ 27 | int main(void) 28 | { 29 | int count = 5; 30 | int arr[5] = {0, 1, 2, 3, 4}; 31 | int *val; 32 | 33 | queue_p queue = get_queue(); 34 | 35 | while (count) { 36 | if (enqueue(queue, &arr[--count]) == FALSE) { 37 | log(ERROR, "enqueue failed!\n"); 38 | destroy_queue(queue); 39 | return -1; 40 | } 41 | 42 | log(DEBUG, "enqueued: arr[%d] = %d\n", count, arr[count]); 43 | } 44 | 45 | count = 5; 46 | 47 | while (count) { 48 | val = dequeue(queue); 49 | if (val) 50 | log(DEBUG, "dequeued: arr[%d] = %d\n", --count, (int)*val); 51 | else 52 | log(ERROR, "dequeue failed!\n"); 53 | } 54 | 55 | destroy_queue(queue); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /include/dlist.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Circular Doubly Linked List abstraction 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "common.h" 22 | 23 | #pragma once 24 | 25 | /* Circular Doubly Linked List ADT */ 26 | typedef struct dlist { 27 | void *data; 28 | struct dlist *next; 29 | struct dlist *prev; 30 | } dlist_t, *dlist_p, **dlist_pp; 31 | 32 | /* Add node at head of list */ 33 | int add_head_dlist(dlist_pp head, dlist_p node); 34 | 35 | /* Get the head of list */ 36 | void *get_head_dlist(dlist_pp head); 37 | 38 | /* Get the tail of list */ 39 | void *get_tail_dlist(dlist_pp head); 40 | 41 | /* Delete the head of list */ 42 | int delete_head_dlist(dlist_pp head); 43 | 44 | /* Delete the tail of list */ 45 | int delete_tail_dlist(dlist_pp head); 46 | 47 | /* Clean up list */ 48 | int destroy_dlist(dlist_pp head); 49 | 50 | /* Count total nodes in list */ 51 | int count_nodes_dlist(dlist_pp head); 52 | -------------------------------------------------------------------------------- /test/test_bst_1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for BST 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | int current_log_level = INFO; 25 | 26 | /* Test BST */ 27 | int main(int argc, char **argv) 28 | { 29 | int count = 0; 30 | bool stop = TRUE; 31 | tree_pp head = NULL; 32 | int arr[] = {10, 20, 30, 40, 50}; 33 | 34 | log(DEBUG, "Calling generate_tree()\n"); 35 | head = generate_tree(arr, sizeof(arr) / sizeof(arr[0])); 36 | 37 | if (argc == 2) 38 | search_BFS(head, atoi(argv[1]), stop); 39 | else 40 | search_BFS(head, 10, stop); 41 | 42 | count = print_tree(*head); 43 | log(INFO, "nodes printed: %d\n", count); 44 | 45 | delete_tree_node(head, 30); 46 | log(INFO, "\n\n"); 47 | 48 | count = print_tree(*head); 49 | log(INFO, "nodes printed: %d\n", count); 50 | 51 | count = destroy_tree(head); 52 | log(INFO, "nodes deleted: %d\n", count); 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /include/tree.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary Search Tree abstraction 3 | * 4 | * Author: Ananya Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "common.h" 22 | 23 | #pragma once 24 | 25 | typedef struct tree { 26 | int data; 27 | struct tree *left; 28 | struct tree *right; 29 | } tree_t, *tree_p, **tree_pp; 30 | 31 | /* Generate tree from an array of input values */ 32 | tree_pp generate_tree(int *arr, int len); 33 | 34 | /* Initalize a tree */ 35 | tree_pp init_tree(void); 36 | 37 | /* Insert a node in tree */ 38 | bool insert_tree_node(tree_pp head, int val); 39 | 40 | /* Delete a node from tree */ 41 | bool delete_tree_node(tree_pp head, int val); 42 | 43 | /* Destroy the tree */ 44 | int destroy_tree(tree_pp head); 45 | 46 | /* Print a tree in preorder */ 47 | int print_tree(tree_p root); 48 | 49 | /* Traverse tree in BFS to find a given value */ 50 | bool search_BFS(tree_pp root, int val, bool stop); 51 | 52 | /* Traverse tree in DFS to find a given value */ 53 | bool search_DFS(tree_pp root, int val, bool stop); 54 | -------------------------------------------------------------------------------- /apilist.txt: -------------------------------------------------------------------------------- 1 | ######################################## 2 | 1. Circular Doubly Linked List [dlist.h] 3 | ######################################## 4 | 5 | int add_head_dlist(dlist_pp head, dlist_p node); 6 | void *get_head_dlist(dlist_pp head); 7 | void *get_tail_dlist(dlist_pp head); 8 | int delete_head_dlist(dlist_pp head); 9 | int delete_tail_dlist(dlist_pp head); 10 | int destroy_dlist(dlist_pp head); 11 | int count_nodes_dlist(dlist_pp head); 12 | 13 | ################## 14 | 2. Queue [queue.h] 15 | ################## 16 | 17 | queue_p get_queue(void); 18 | bool enqueue(queue_p queue, void *val); 19 | void *dequeue(queue_p queue); 20 | bool isQueueEmpty(queue_p queue); 21 | bool destroy_queue(queue_p queue); 22 | 23 | ################## 24 | 3. Stack [stack.h] 25 | ################## 26 | 27 | stack_p get_stack(void); 28 | bool push(stack_p stack, void *val); 29 | void *pop(stack_p stack); 30 | bool isStackEmpty(stack_p stack); 31 | bool destroy_stack(stack_p stack); 32 | 33 | ############################## 34 | 4. Binary Search Tree [tree.h] 35 | ############################## 36 | 37 | tree_pp generate_tree(int *arr, int len); 38 | tree_pp init_tree(void); 39 | bool insert_tree_node(tree_pp head, int val); 40 | bool delete_tree_node(tree_pp head, int val); 41 | int destroy_tree(tree_pp head); 42 | int print_tree(tree_p root); 43 | int search_BFS(tree_pp root, int val, bool stop); 44 | int search_DFS(tree_pp root, int val, bool stop); 45 | 46 | ################### 47 | 5. AVL Tree [avl.h] 48 | ################### 49 | 50 | avl_pp generate_avl(int *arr, int len); 51 | avl_pp init_avl(void); 52 | bool insert_avl_node(avl_pp head, int val); 53 | bool delete_avl_node(avl_pp head, int val); 54 | int destroy_avl(avl_pp head); 55 | int print_avl(avl_p root, avl_p parent); 56 | int search_BFS_avl(avl_pp root, int val, bool stop); 57 | -------------------------------------------------------------------------------- /test/test_avl_1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for AVL tree 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | int current_log_level = INFO; 25 | 26 | int main(int argc, char **argv) 27 | { 28 | int count = 0; 29 | 30 | bool stop = FALSE; 31 | 32 | avl_pp head = init_avl(); 33 | int arr[] = {30, 110, 10, 90, 120, 150, 70, 34 | 140, 40, 130, 20, 50, 100, 80, 60}; 35 | /* int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 36 | 90, 100, 110, 120, 130, 140, 150}; */ 37 | int len = sizeof(arr) / sizeof(arr[0]); 38 | 39 | for (; count < len; ++count) { 40 | if (insert_avl_node(head, arr[count], 20) == FALSE) { 41 | log(ERROR, "Insertion failed.\n"); 42 | destroy_avl(head); 43 | return 0; 44 | } 45 | } 46 | 47 | if (argc == 2) 48 | search_BFS_avl(head, atoi(argv[1]), stop); 49 | else 50 | search_BFS_avl(head, 10, stop); 51 | 52 | count = print_avl(*head, *head); 53 | log(INFO, "nodes printed: %d\n\n", count); 54 | 55 | if (delete_avl_node(head, 110) == TRUE) 56 | log(INFO, "AVL node deleted\n\n"); 57 | count = print_avl(*head, *head); 58 | log(INFO, "nodes printed: %d\n", count); 59 | 60 | count = destroy_avl(head); 61 | log(INFO, "nodes deleted: %d\n", count); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /test/test_dlist_1.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for dlist 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | int current_log_level = INFO; 25 | 26 | /* Test dlist */ 27 | int main(void) 28 | { 29 | int count = 5; 30 | 31 | dlist_p *head_pp = calloc(1, sizeof(dlist_p *)); 32 | 33 | while (count) { 34 | dlist_p node_p = calloc(1, sizeof(dlist_t)); 35 | 36 | log(DEBUG, "node address %p\n", node_p); 37 | if (add_head_dlist(head_pp, node_p) == -1) { 38 | log(ERROR, "add_head_dlist failed!\n"); 39 | return -1; 40 | } 41 | 42 | log(DEBUG, "Node added\n"); 43 | 44 | count--; 45 | } 46 | 47 | log(DEBUG, "Total nodes1: %d\n", count_nodes_dlist(head_pp)); 48 | 49 | if (delete_head_dlist(head_pp)) { 50 | log(DEBUG, "Total nodes after head delete: %d\n", 51 | count_nodes_dlist(head_pp)); 52 | } else { 53 | log(ERROR, "delete_head_dlist failed!\n"); 54 | return -1; 55 | } 56 | 57 | log(DEBUG, "Total nodes2: %d\n", count_nodes_dlist(head_pp)); 58 | 59 | if (delete_tail_dlist(head_pp)) { 60 | log(DEBUG, "Total nodes after tail delete: %d\n", 61 | count_nodes_dlist(head_pp)); 62 | } else { 63 | log(ERROR, "delete_tail_dlist failed!\n"); 64 | return -1; 65 | } 66 | 67 | log(DEBUG, "Nodes destroyed: %d\n", destroy_dlist(head_pp)); 68 | log(DEBUG, "Total nodes: %d\n", count_nodes_dlist(head_pp)); 69 | 70 | free(head_pp); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /src/stack.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Stack implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "stack.h" 22 | 23 | /* 24 | * Create a new Stack 25 | * Alocate a head node 26 | */ 27 | stack_p get_stack(void) 28 | { 29 | stack_p stack = calloc(1, sizeof(stack_t)); 30 | 31 | stack->head = calloc(1, sizeof(dlist_pp)); 32 | return stack; 33 | } 34 | 35 | /* 36 | * Push a value to Stack 37 | * Allocates a new dlist node and inserts value 38 | */ 39 | bool push(stack_p stack, void *val) 40 | { 41 | dlist_p nodeptr = calloc(1, sizeof(dlist_t)); 42 | 43 | nodeptr->data = val; 44 | 45 | return (add_head_dlist(stack->head, nodeptr) == 1); /* Last In */ 46 | } 47 | 48 | /* 49 | * Pop a value from Stack 50 | * Deallocates the dlist node holding the value 51 | */ 52 | void *pop(stack_p stack) 53 | { 54 | void *data = get_head_dlist(stack->head); /* First out */ 55 | 56 | if (delete_head_dlist(stack->head) == -1) 57 | log(DEBUG, "head or first node is NULL!\n"); 58 | 59 | return data; 60 | } 61 | 62 | /* 63 | * Check if a stack has any elements 64 | */ 65 | bool isStackEmpty(stack_p stack) 66 | { 67 | if (get_head_dlist(stack->head)) 68 | return TRUE; 69 | 70 | return FALSE; 71 | } 72 | 73 | /* 74 | * Deallocate all dlist nodes 75 | * Destroy Stack 76 | */ 77 | bool destroy_stack(stack_p stack) 78 | { 79 | if (destroy_dlist(stack->head) == -1) 80 | return FALSE; 81 | 82 | free(stack->head); 83 | free(stack); 84 | 85 | return TRUE; 86 | } 87 | -------------------------------------------------------------------------------- /src/queue.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Queue implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "queue.h" 22 | 23 | /* 24 | * Create a new Queue 25 | * Alocate a head node 26 | */ 27 | queue_p get_queue(void) 28 | { 29 | queue_p queue = calloc(1, sizeof(queue_t)); 30 | 31 | queue->head = calloc(1, sizeof(dlist_pp)); 32 | return queue; 33 | } 34 | 35 | /* 36 | * Add a value to Queue 37 | * Allocates a new dlist node and inserts value 38 | */ 39 | bool enqueue(queue_p queue, void *val) 40 | { 41 | dlist_p nodeptr = calloc(1, sizeof(dlist_t)); 42 | 43 | nodeptr->data = val; 44 | 45 | return (add_head_dlist(queue->head, nodeptr) == 1); /* Last In */ 46 | } 47 | 48 | /* 49 | * Remove the value at the front of the Queue 50 | * Deallocates the dlist node holding the value 51 | */ 52 | void *dequeue(queue_p queue) 53 | { 54 | void *data = get_tail_dlist(queue->head); /* Last Out */ 55 | 56 | if (delete_tail_dlist(queue->head) == -1) 57 | log(DEBUG, "head or first node is NULL!\n"); 58 | 59 | return data; 60 | } 61 | 62 | /* 63 | * Check if a Queue has any elements 64 | */ 65 | bool isQueueEmpty(queue_p queue) 66 | { 67 | if (get_head_dlist(queue->head)) 68 | return TRUE; 69 | 70 | return FALSE; 71 | } 72 | 73 | /* 74 | * Deallocate all dlist nodes 75 | * Destroy Queue 76 | */ 77 | bool destroy_queue(queue_p queue) 78 | { 79 | if (destroy_dlist(queue->head) == -1) 80 | return FALSE; 81 | 82 | free(queue->head); 83 | free(queue); 84 | 85 | return TRUE; 86 | } 87 | -------------------------------------------------------------------------------- /include/common.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Common header file for dslib 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "log.h" 22 | 23 | #pragma once 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | /* Introduce boolean type */ 32 | #define TRUE 1 33 | #define FALSE !TRUE 34 | 35 | #define LEFT 0 36 | #define RIGHT 1 37 | 38 | typedef unsigned char bool; 39 | 40 | /*=======================================================*/ 41 | /* Syncronize for ThreadSafe APIs start here */ 42 | /*=======================================================*/ 43 | 44 | enum semName {wantWrite=0,readWorking=1,writeWorking=2}; 45 | 46 | int semInit(); 47 | 48 | /*#######################################*/ 49 | /* Lock/unlock for writers function */ 50 | /*#######################################*/ 51 | int lockWriteSem(int semId); 52 | 53 | int unlockWriteSem(int semId); 54 | 55 | /*#######################################*/ 56 | /* Lock/unlock for readers function */ 57 | /*#######################################*/ 58 | int lockReadSem(int semId); 59 | 60 | int unlockReadSem(int semId); 61 | 62 | //semInfo print 63 | void semInfo(int semId); 64 | 65 | 66 | /* 67 | The scheme of synchronization is easy: (i use system 5) 68 | There are 3 semaphore: wantWrite,readWorking and writeWorking (last like mutex, and the first two are counter in fact) 69 | 70 | READER: 71 | If more than one read-funx(like search) need to read data it will be wait until wantWrite!=0. 72 | ATOMICALLY it add at readWorking +1, to start only if no one write are current at working. 73 | After, ALL READER-funx can be work and finally decrease readWorking counter (this in concurrency). 74 | 75 | WRITER: 76 | to start it add wantWrite +1, (to signal at new reader, it si necessary to waiting) 77 | after the writers WAIT until all reader just at work finish. 78 | then, writer-funx can lock writeWorking to write one at time (is a mutex), 79 | enter in critic section, and at the end unlock writeWorking. 80 | Finally decrement wantWrite -1, and finish. 81 | 82 | */ 83 | -------------------------------------------------------------------------------- /include/avl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AVL Tree abstraction 3 | * Ref: https://en.wikipedia.org/wiki/AVL_tree 4 | * 5 | * Author: Arun Prakash Jana 6 | * Copyright (C) 2015 by Arun Prakash Jana 7 | * 8 | * This program is free software: you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation, either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with dslib. If not, see . 20 | */ 21 | 22 | #include "common.h" 23 | 24 | #pragma once 25 | 26 | typedef struct avl { 27 | int keyNode; 28 | int data; 29 | struct avl *left; 30 | struct avl *right; 31 | int height; 32 | } avl_t, *avl_p, **avl_pp; 33 | 34 | /* Generate AVL tree from an array of input values */ 35 | avl_pp generate_avl(int *arr, int len); 36 | 37 | /* Initialize an AVL tree */ 38 | avl_pp init_avl(void); 39 | 40 | /* Insert a node in AVL tree */ 41 | bool insert_avl_node(avl_pp head, int key, int data); 42 | 43 | 44 | /* Delete a node from AVL tree */ 45 | bool delete_avl_node(avl_pp head, int key); 46 | 47 | /* Destroy the tree */ 48 | int destroy_avl(avl_pp head); 49 | // avl will be destroy isn't necessary sincronize it (is better not destroy) 50 | 51 | /* Print a tree in preorder */ 52 | int print_avl(avl_p root, avl_p parent); 53 | 54 | /* Traverse tree in BFS to find a given value */ 55 | int search_BFS_avl(avl_pp root, int key, bool stop); 56 | 57 | /*=======================================================*/ 58 | /* Library ThreadSafe APIs start here */ 59 | /*=======================================================*/ 60 | 61 | //The struct is a generalization of avl_pp, to include for every tree one semaphore 62 | typedef struct avlThSafe { 63 | avl_pp avlRoot; 64 | int semId; 65 | } avl_pp_S; 66 | 67 | /* Generate AVL tree from an array of input values */ 68 | avl_pp_S generate_avl_S(int *arr, int len); 69 | 70 | /* Initialize an AVL tree */ 71 | avl_pp_S init_avl_S(void); 72 | 73 | /* Insert a node in AVL tree */ 74 | bool insert_avl_node_S(avl_pp_S head, int key, int data); 75 | 76 | /* Delete a node from AVL tree */ 77 | bool delete_avl_node_S(avl_pp_S head, int key); 78 | 79 | /* Destroy the tree */ 80 | /** [][] avl will be destroy isn't necessary sincronize it (is better not destroy) **/ 81 | 82 | /* Print a tree in preorder, start by root */ 83 | int print_avl_S(avl_pp_S root); 84 | 85 | /* Traverse tree in BFS to find a given value */ 86 | int search_BFS_avl_S(avl_pp_S root, int key, bool stop); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dslib 2 | `dslib` is a library of cohesive data structures. The goal of `dslib` is to demonstrate how complex data structures (and related algorithms) can be developed by reusing simpler ones. In general, textbooks come with numerous unrelated examples, each relevant to a specific data structure. `dslib`, on the other hand, grows by building on the elementary data structures. 3 | 4 | The core component is a circular doubly linked list. Library-internal data structures are dynamically (de)allocated. 5 | 6 | Most of the code conforms to the Linux kernel coding standards (verified against *checkpatch.pl*), other than a few unavoidable instances. 7 | 8 | `dslib` is an academic library. However, we'll be glad if someone finds any other application of it. 9 | 10 |

11 | Donate via PayPal! 12 |

13 | 14 | ### Table of Contents 15 | - [Building blocks](#building-blocks) 16 | - [APIs](#apis) 17 | - [Thread-safety](#thread-safety) 18 | - [Compilation](#compilation) 19 | - [Testing](#testing) 20 | - [Developers](#developers) 21 | - [Contributions](#contributions) 22 | 23 | ### Building blocks 24 | | DS | Description | 25 | | --- | --- | 26 | | dlist | Circular doubly linked list. Node has next, prev and data (`void *`, caller (de)allocates) pointers. | 27 | | queue | Builds on top of dlist. Each element is a dlist node pointing to the value inserted in the queue. | 28 | | stack | Builds on top of dlist. Each element is a dlist node pointing to the value pushed in the stack. | 29 | | tree | A binary search tree, stores integers. | 30 | | AVL | An AVL tree implementation, stores integers. | 31 | | BFS | Iterative Breadth-first search for tree and AVL implemented using the queue. | 32 | | DFS | Iterative Depth-first search for tree implemented using the stack. | 33 | 34 | There are test cases for each DS. Though not very organized, they provide an insight into the usage of `dslib`. 35 | 36 | ### APIs 37 | A complete list of APIs can be found in [apilist.txt](https://github.com/jarun/dslib/blob/master/apilist.txt). Most of the APIs are iterative. 38 | The following 2 APIs are recursive and the iterative implementations are left as an exercise: 39 | 40 | ``` 41 | bool delete_tree_node(tree_pp head, int val); 42 | bool delete_avl_node(avl_pp head, int val); 43 | ``` 44 | 45 | ### Thread-safety 46 | Currently the Thread-Safe mode is implemented only for AVL. The lock functions are in common.h and common.c and it's easy to extend thread-safety in other structures. 47 | 48 | ### Compilation 49 | The following compilation steps are tested on Ubuntu 14.04.4 x86_64: 50 | 51 | $ git clone https://github.com/jarun/dslib/ 52 | $ cd dslib 53 | $ make 54 | 55 | To install `dslib`, run: 56 | 57 | $ sudo make install 58 | 59 | To remove `dslib` from your system, run: 60 | 61 | $ sudo make uninstall 62 | 63 | Clean up (cleans test executables too): 64 | 65 | $ make clean 66 | 67 | ### Testing 68 | Make sure `dslib` is installed. To compile test cases under `test` subdirectory: 69 | 70 | $ sudo make install 71 | $ make test 72 | 73 | Only informative logs are enabled. For DEBUG logs, set: 74 | 75 | int current_log_level = DEBUG; 76 | 77 | in the source test file. 78 | 79 | ### Developers 80 | - [Arun Prakash Jana](https://github.com/jarun) (Copyright © 2015) 81 | - [Ananya Jana](https://github.com/ananyajana) 82 | 83 | ### Contributions 84 | Contributions are welcome! We would love to see more data structures and APIs added to `dslib`. 85 | -------------------------------------------------------------------------------- /test/avl_Thread_Safe_Test.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Test cases for AVL-ThreadSafe tree 3 | * 4 | * Author: Emanuele Alfano 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | /* 22 | * This demo works in posix, it create "nSearch" thread and him call forEver 23 | * "search_BFS_avl_S", with ctrl+c you send a lockWrite, 24 | * with ctrl+z you send unlockWrite 25 | * 26 | * The function must send in order: 27 | * 1° Lock-write 28 | * 2° Unlock-write 29 | * 30 | * Is also possible send different configuratio: 31 | * 1° Lock-write 32 | * 2° Lock-write 33 | * 3° Lock-write 34 | * 4° Unlock-write 35 | * 5° Unlock-write 36 | * 6° Unlock-write 37 | * ... 38 | * 39 | * To end script type ctrl+\ (sigKill) 40 | * 41 | * 42 | * Is important to see that, when first writeLock arrive, search thread just at work 43 | * finish his work and finaly the write lock arrive 44 | */ 45 | 46 | #define nSearch 50 47 | 48 | #include 49 | #include "avl.h" 50 | 51 | #include 52 | #include 53 | #include 54 | #include 55 | 56 | int current_log_level = DEBUG; 57 | avl_pp_S head; 58 | 59 | int n_nodeInsert; 60 | int searchRange; 61 | int writePending; 62 | 63 | void *searchTh(void *info) 64 | { 65 | int id = *(int *)info; 66 | int keySearch; 67 | int found; 68 | 69 | while (1) { 70 | keySearch = (int) random() % searchRange; 71 | 72 | found = search_BFS_avl_S(head, keySearch, TRUE); 73 | 74 | printf("TH-Search %d Search key %d and ret %d\n", id, keySearch, found); 75 | 76 | usleep(1000000*random()%100); //random wait between 1 and 100 ms 77 | } 78 | free(info); 79 | 80 | return NULL; 81 | } 82 | 83 | void lockWriteSem_sig(int sig) 84 | { 85 | writePending++; 86 | printf("\n\t****sigINT receive sig = %d; n°writePending = %d\n\n", sig, writePending); 87 | lockWriteSem(head.semId); 88 | printf("\n\t####sigInt lock Write TAKE\n"); 89 | } 90 | 91 | void unlockWriteSem_sig(int sig) 92 | { 93 | //note, if writePending = 0, this signal stay in wait until arrive one lockWriteSem_sig, 94 | //but the library wasn't design tu solve this!!! It work only if every Writer, on the Start lock the tree, and at the End unlock then. 95 | printf("\n\t#(sigTSTP) receive sig = %d\n\n", sig); 96 | unlockWriteSem(head.semId); 97 | writePending--; 98 | printf("\n\t#(sigTSTP) unlock Write; n°writePending = %d\n", writePending); 99 | } 100 | 101 | int main(void) 102 | { 103 | 104 | signal(SIGINT, lockWriteSem_sig); 105 | signal(SIGTSTP, unlockWriteSem_sig); 106 | head = init_avl_S(); 107 | 108 | n_nodeInsert = nSearch * 10; 109 | searchRange = n_nodeInsert * 2; 110 | 111 | 112 | for (int count = 0; count < n_nodeInsert; count++) { 113 | if (insert_avl_node_S(head, count, (int)random() % searchRange) == FALSE) { 114 | log(ERROR, "Insertion failed.\n"); 115 | destroy_avl(head.avlRoot); 116 | return 0; 117 | } 118 | } 119 | print_avl_S(head); 120 | //sleep(20); //to give time to see tree print 121 | 122 | pthread_t tid; 123 | 124 | printf("Start search Thread\n"); 125 | for (int count = 0; count < nSearch; count++) { 126 | int *i = malloc(sizeof(int)); 127 | *i = count; 128 | pthread_create(&tid, NULL, searchTh, i); 129 | } 130 | while (1) 131 | pause(); 132 | return 0; 133 | } 134 | -------------------------------------------------------------------------------- /src/common.c: -------------------------------------------------------------------------------- 1 | // 2 | // Created by alfylinux on 21/10/18. 3 | // 4 | 5 | #include "common.h" 6 | 7 | 8 | int semInit() 9 | { 10 | int semId = semget(IPC_PRIVATE,3, IPC_CREAT | IPC_EXCL | 0666); 11 | if (semId == -1) 12 | { 13 | perror("Create Sem-s take error:"); 14 | return -1; 15 | } 16 | 17 | //enum semName {wantWrite=0,readWorking=1,writeWorking=2}; number is Id of sem 18 | unsigned short semStartVal[3] = {0, 0, 1}; 19 | 20 | //setup 3 semaphore in system5 21 | if (semctl(semId, 0, SETALL, semStartVal)) 22 | { 23 | perror("set Sem take error:"); 24 | return -1; 25 | } 26 | 27 | printf("SEMAFORO Created\n"); 28 | semInfo(semId); 29 | 30 | return semId; 31 | } 32 | 33 | int lockWriteSem(int semId) 34 | { 35 | struct sembuf sem; 36 | sem.sem_flg = SEM_UNDO; 37 | 38 | //increase counter wantWrite 39 | sem.sem_num = wantWrite; 40 | sem.sem_op = +1; 41 | SEM_wantWrite: 42 | if (semop(semId, &sem, 1)) 43 | { 44 | switch (errno) 45 | { 46 | case EINTR: 47 | goto SEM_wantWrite; 48 | break; 49 | default: 50 | perror("increase wantWrite semCount error:"); 51 | return -1; 52 | break; 53 | } 54 | } 55 | 56 | //wait until =0 readerWork 57 | sem.sem_num = readWorking; 58 | sem.sem_op = 0; 59 | 60 | SEM_waitReaders: 61 | if (semop(semId, &sem, 1)) 62 | { 63 | switch (errno) 64 | { 65 | case EINTR: 66 | goto SEM_waitReaders; 67 | break; 68 | default: 69 | perror("wait until 0 readWorking take error:"); 70 | return -1; 71 | break; 72 | } 73 | } 74 | //wait noThread already work 75 | sem.sem_num = writeWorking; 76 | sem.sem_op = -1; 77 | 78 | SEM_writeWorking: 79 | if (semop(semId, &sem, 1)) 80 | { 81 | switch (errno) 82 | { 83 | case EINTR: 84 | goto SEM_writeWorking; 85 | break; 86 | default: 87 | perror("lock writeWorking error:"); 88 | return -1; 89 | break; 90 | } 91 | } 92 | return 0; 93 | } 94 | 95 | int unlockWriteSem(int semId) 96 | { 97 | struct sembuf sem; 98 | sem.sem_flg = SEM_UNDO; 99 | 100 | //signal finish writing work 101 | sem.sem_num = writeWorking; 102 | sem.sem_op = 1; 103 | 104 | SEM_writeWorking: 105 | if (semop(semId, &sem, 1)) 106 | { 107 | switch (errno) 108 | { 109 | case EINTR: 110 | goto SEM_writeWorking; 111 | break; 112 | default: 113 | perror("unlock writeWorking error:"); 114 | return -1; 115 | break; 116 | } 117 | } 118 | //reduce counter of wantWrite 119 | sem.sem_num = wantWrite; 120 | sem.sem_op = -1; 121 | 122 | SEM_wantWrite: 123 | if (semop(semId, &sem, 1)) 124 | { 125 | switch (errno) 126 | { 127 | case EINTR: 128 | goto SEM_wantWrite; 129 | break; 130 | default: 131 | perror("decrease wantWrite semCount error:"); 132 | return -1; 133 | break; 134 | } 135 | } 136 | return 0; 137 | } 138 | 139 | 140 | int lockReadSem(int semId) 141 | { 142 | struct sembuf sem[2]; 143 | sem[0].sem_num = wantWrite; 144 | sem[0].sem_flg = SEM_UNDO; 145 | sem[1].sem_num = readWorking; 146 | sem[1].sem_flg = SEM_UNDO; 147 | 148 | //to be sure not concurrency problem, read Thread must be wait until no writes works, and instantly increase his counter 149 | sem[0].sem_op = 0; 150 | sem[1].sem_op = +1; 151 | SEM_wantWrite_readWorking: 152 | if (semop(semId, sem, 2)) 153 | { 154 | switch (errno) 155 | { 156 | case EINTR: 157 | goto SEM_wantWrite_readWorking; 158 | break; 159 | default: 160 | perror("lockRead sem take error:"); 161 | return -1; 162 | break; 163 | } 164 | } 165 | 166 | return 0; 167 | } 168 | 169 | int unlockReadSem(int semId) 170 | { 171 | struct sembuf sem; 172 | sem.sem_flg = SEM_UNDO; 173 | sem.sem_num = readWorking; 174 | sem.sem_op = -1; 175 | 176 | SEM_readWorking: 177 | if (semop(semId, &sem, 1)) 178 | { 179 | switch (errno) 180 | { 181 | case EINTR: 182 | goto SEM_readWorking; 183 | break; 184 | default: 185 | perror("unlockRead sem take error:"); 186 | return -1; 187 | break; 188 | } 189 | } 190 | return 0; 191 | } 192 | 193 | void semInfo(int semId) 194 | { 195 | unsigned short semInfo[3]; 196 | semctl(semId, 0, GETALL, semInfo); 197 | //enum semName {wantWrite=0,readWorking=1,writeWorking=2}; 198 | printf("\nsem writeWorking=%d\n", semInfo[writeWorking]); 199 | printf("sem readWorking=%d\n", semInfo[readWorking]); 200 | printf("sem wantWrite=%d\n", semInfo[wantWrite]); 201 | } -------------------------------------------------------------------------------- /src/dlist.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Circular Doubly Linked List implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "dlist.h" 22 | 23 | /* 24 | * Add a node to the head of dlist 25 | */ 26 | int add_head_dlist(dlist_pp head, dlist_p node) 27 | { 28 | if (!node) { 29 | log(ERROR, "node is NULL!\n"); 30 | return -1; 31 | } 32 | 33 | if (!head) { 34 | log(ERROR, "head is NULL!\n"); 35 | return -1; 36 | } 37 | 38 | if (!*head) { 39 | node->next = node; 40 | node->prev = node; 41 | *head = node; 42 | 43 | return 1; 44 | } 45 | 46 | node->next = *head; /* Current head become head->next */ 47 | node->prev = (*head)->prev; 48 | (*head)->prev->next = node; 49 | (*head)->prev = node; 50 | *head = node; 51 | 52 | return 1; 53 | } 54 | 55 | /* 56 | * Get the value in the head node of dlist 57 | * The node is not deleted 58 | */ 59 | void *get_head_dlist(dlist_pp head) 60 | { 61 | if (!head || !*head) { 62 | log(DEBUG, "head or first node is NULL!\n"); 63 | return NULL; 64 | } 65 | 66 | return (*head)->data; 67 | } 68 | 69 | /* 70 | * Get the value in the tail node of dlist 71 | * The node is not deleted 72 | */ 73 | void *get_tail_dlist(dlist_pp head) 74 | { 75 | if (!head || !*head) { 76 | log(DEBUG, "head or first node is NULL!\n"); 77 | return NULL; 78 | } 79 | 80 | return (*head)->prev->data; 81 | } 82 | 83 | /* 84 | * Delete the head node of dlist 85 | */ 86 | int delete_head_dlist(dlist_pp head) 87 | { 88 | dlist_p tmp; 89 | 90 | if (!head || !*head) { 91 | log(DEBUG, "No nodes to delete!\n"); 92 | return -1; 93 | } 94 | 95 | if (*head == (*head)->next) { 96 | free(*head); 97 | *head = NULL; 98 | return 1; 99 | } 100 | 101 | tmp = *head; 102 | (*head)->data = NULL; 103 | (*head)->prev->next = (*head)->next; 104 | (*head)->next->prev = (*head)->prev; 105 | *head = (*head)->next; /* head->next becomes next head */ 106 | 107 | free(tmp); 108 | 109 | return 1; 110 | } 111 | 112 | /* 113 | * Delete the tail node of dlist 114 | */ 115 | int delete_tail_dlist(dlist_pp head) 116 | { 117 | dlist_p tmp; 118 | 119 | if (!head || !*head) { 120 | log(DEBUG, "head or first node is NULL!\n"); 121 | return -1; 122 | } 123 | 124 | if (*head == (*head)->next) { 125 | free(*head); 126 | *head = NULL; 127 | return 1; 128 | } 129 | 130 | tmp = (*head)->prev; 131 | tmp->data = NULL; 132 | tmp->prev->next = tmp->next; /* tail->prev becomes new tail */ 133 | tmp->next->prev = tmp->prev; 134 | 135 | free(tmp); 136 | 137 | return 1; 138 | } 139 | 140 | /* 141 | * Deallocate all memory and destroy the dlist 142 | * Returns the number of nodes deleted 143 | */ 144 | int destroy_dlist(dlist_pp head) 145 | { 146 | dlist_p tmp; 147 | int deleted = 0; 148 | 149 | if (!head) { 150 | log(DEBUG, "head is NULL.\n"); 151 | return -1; 152 | } 153 | 154 | if (!*head) { 155 | log(DEBUG, "No nodes to delete.\n"); 156 | return 0; 157 | } 158 | 159 | /* Set tail->next to NULL to end deletion loop */ 160 | (*head)->prev->next = NULL; 161 | 162 | while (*head) { 163 | tmp = *head; 164 | (*head)->data = NULL; 165 | (*head)->prev = NULL; 166 | *head = (*head)->next; 167 | 168 | free(tmp); 169 | deleted++; 170 | } 171 | 172 | return deleted; 173 | } 174 | 175 | /* 176 | * Count the total number of nodes in the dlist 177 | */ 178 | int count_nodes_dlist(dlist_pp head) 179 | { 180 | dlist_p tmp; 181 | int count = 0; 182 | 183 | if (!head || !*head) { 184 | log(DEBUG, "head or first node is NULL!\n"); 185 | return -1; 186 | } 187 | 188 | tmp = *head; 189 | 190 | do { 191 | count++; 192 | tmp = tmp->next; 193 | } while (tmp != *head); 194 | 195 | return count; 196 | } 197 | -------------------------------------------------------------------------------- /src/tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Iterative Binary Search Tree implementation 3 | * 4 | * Author: Ananya Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "queue.h" 22 | #include "stack.h" 23 | #include "tree.h" 24 | 25 | /* 26 | * Delete all nodes of a tree 27 | */ 28 | int delete_tree_nodes(tree_p root) 29 | { 30 | int count = 0; 31 | 32 | if (!root) { 33 | log(ERROR, "root invalid.\n"); 34 | return -1; 35 | } 36 | 37 | if (root->left) 38 | count += delete_tree_nodes(root->left); 39 | 40 | if (root->right) 41 | count += delete_tree_nodes(root->right); 42 | 43 | free(root); 44 | root = NULL; 45 | 46 | return ++count; 47 | } 48 | 49 | /*=======================================================*/ 50 | /* Library exposed APIs start here */ 51 | /*=======================================================*/ 52 | 53 | /* 54 | * Generate a tree from an array of integers 55 | */ 56 | tree_pp generate_tree(int *arr, int len) 57 | { 58 | int i = 0; 59 | tree_pp head = NULL; 60 | 61 | if (!arr || !len) { 62 | log(ERROR, "Invalid array.\n"); 63 | return NULL; 64 | } 65 | 66 | head = init_tree(); 67 | 68 | for (; i < len; i++) { 69 | if (insert_tree_node(head, arr[i]) == FALSE) { 70 | log(ERROR, "Insertion failed.\n"); 71 | destroy_tree(head); 72 | return NULL; 73 | } 74 | } 75 | 76 | return head; 77 | } 78 | 79 | /* 80 | * Initialize a tree with empty root node 81 | */ 82 | tree_pp init_tree(void) 83 | { 84 | tree_pp head = calloc(1, sizeof(tree_p)); 85 | *head = NULL; 86 | 87 | return head; 88 | } 89 | 90 | /* 91 | * Insert a new node into tree 92 | */ 93 | bool insert_tree_node(tree_pp head, int val) 94 | { 95 | tree_p root = NULL; 96 | 97 | if (!head) { 98 | log(ERROR, "Initialize tree first.\n"); 99 | return FALSE; 100 | } 101 | 102 | root = *head; 103 | 104 | while (root) { 105 | if (val < root->data) { 106 | if (!root->left) { 107 | root->left = calloc(1, sizeof(tree_t)); 108 | root = root->left; 109 | root->data = val; 110 | return TRUE; 111 | } 112 | 113 | root = root->left; 114 | } else if (val > root->data) { /* Insert greater elements in right subtree */ 115 | if (!root->right) { 116 | root->right = calloc(1, sizeof(tree_t)); 117 | root = root->right; 118 | root->data = val; 119 | return TRUE; 120 | } 121 | 122 | root = root->right; 123 | } else { 124 | log(ERROR, "BST must have unique values.\n"); 125 | break; 126 | } 127 | } 128 | 129 | if (!*head) { 130 | root = (tree_p) calloc(1, sizeof(tree_t)); 131 | root->data = val; 132 | *head = root; 133 | 134 | return TRUE; 135 | } 136 | 137 | return FALSE; 138 | } 139 | 140 | /* 141 | * Delete a node from tree 142 | */ 143 | bool delete_tree_node(tree_pp head, int val) 144 | { 145 | tree_p root = NULL; 146 | tree_p prev = NULL; 147 | int direction; 148 | 149 | if (!head) { 150 | log(ERROR, "Initialize tree first.\n"); 151 | return FALSE; 152 | } 153 | 154 | root = *head; 155 | 156 | while (root) { 157 | if (val < root->data) { 158 | if (!root->left) 159 | break; 160 | 161 | prev = root; 162 | direction = LEFT; 163 | root = root->left; 164 | } else if (val > root->data) { /* Greater elements are in right subtree */ 165 | if (!root->right) 166 | break; 167 | 168 | prev = root; 169 | direction = RIGHT; 170 | root = root->right; 171 | } else { /* Match found */ 172 | if (!root->left) { 173 | if (prev) { 174 | if (direction == LEFT) 175 | prev->left = root->right; 176 | else 177 | prev->right = root->right; 178 | } else /* This was the root node */ 179 | *head = root->right; 180 | 181 | free(root); 182 | return TRUE; 183 | } else if (!root->right) { 184 | if (prev) { 185 | if (direction == LEFT) 186 | prev->left = root->left; 187 | else 188 | prev->right = root->left; 189 | } else /* This was the root node */ 190 | *head = root->left; 191 | 192 | free(root); 193 | return TRUE; 194 | } else { /* Both subtrees have children */ 195 | /* Delete inorder successor */ 196 | tree_p min = root->right; 197 | while (min->left) 198 | min = min->left; 199 | 200 | root->data = min->data; 201 | /* Let's use some recursion here */ 202 | delete_tree_node(&(root->right), min->data); 203 | 204 | return TRUE; 205 | } 206 | } 207 | } 208 | 209 | /* Fall through if root is NULL */ 210 | return FALSE; 211 | } 212 | 213 | /* 214 | * Destroy a tree 215 | */ 216 | int destroy_tree(tree_pp head) 217 | { 218 | int count = 0; 219 | 220 | if (!head) { 221 | log(ERROR, "head invalid.\n"); 222 | return -1; 223 | } 224 | 225 | count = delete_tree_nodes(*head); 226 | 227 | free(head); 228 | head = NULL; 229 | 230 | return count; 231 | } 232 | 233 | /* 234 | * Print the values in a tree in preorder 235 | */ 236 | int print_tree(tree_p root) 237 | { 238 | int count = 0; 239 | 240 | if (!root) { 241 | log(ERROR, "root invalid.\n"); 242 | return -1; 243 | } 244 | 245 | log(DEBUG, "keyNode: %d.\n", root->data); 246 | ++count; 247 | 248 | if (root->left) 249 | count += print_tree(root->left); 250 | if (root->right) 251 | count += print_tree(root->right); 252 | 253 | return count; 254 | } 255 | 256 | /* 257 | * Tree Breadth First Search implementation 258 | * Implements iterative search using a Queue 259 | * Checks for a match before adding a node to Queue 260 | * 261 | * PARAMS 262 | * ------ 263 | * root: pointer to the root node pointer of a tree 264 | * val : value to search 265 | * stop: stop if val is found 266 | */ 267 | bool search_BFS(tree_pp root, int val, bool stop) 268 | { 269 | tree_p node = NULL; 270 | queue_p queue = NULL; 271 | int ret = FALSE; 272 | 273 | if (!root || !*root) { 274 | log(ERROR, "tree or root node is NULL!\n"); 275 | return FALSE; 276 | } 277 | 278 | /* Check for a match in root node */ 279 | node = *root; 280 | if (node->data == val) { 281 | log(INFO, "FOUND %d\n", val); 282 | 283 | if (stop) 284 | return TRUE; 285 | } 286 | 287 | queue = get_queue(); 288 | 289 | /* Add root node to Queue */ 290 | if (!enqueue(queue, *root)) { 291 | log(ERROR, "enqueue failed!\n"); 292 | destroy_queue(queue); 293 | return FALSE; 294 | } 295 | 296 | /* Loop through all nodes in the Queue */ 297 | while ((node = dequeue(queue)) != NULL) { 298 | log(INFO, "tracking...\n"); 299 | 300 | /* Process left child of node */ 301 | if (node->left) { 302 | if (node->left->data == val) { 303 | log(INFO, "FOUND %d\n", val); 304 | ret = TRUE; 305 | 306 | if (stop) 307 | break; 308 | } 309 | 310 | /* Add left child to Queue */ 311 | if (!enqueue(queue, node->left)) { 312 | log(ERROR, "enqueue failed!\n"); 313 | destroy_queue(queue); 314 | return FALSE; 315 | } 316 | } 317 | 318 | /* Process right child of node */ 319 | if (node->right) { 320 | if (node->right->data == val) { 321 | log(INFO, "FOUND %d\n", val); 322 | ret = TRUE; 323 | 324 | if (stop) 325 | break; 326 | } 327 | 328 | /* Add right child to Queue */ 329 | if (!enqueue(queue, node->right)) { 330 | log(ERROR, "enqueue failed!\n"); 331 | destroy_queue(queue); 332 | return FALSE; 333 | } 334 | } 335 | } 336 | 337 | /* Report if no match was found */ 338 | if (!ret) 339 | log(INFO, "NOT FOUND\n"); 340 | 341 | destroy_queue(queue); 342 | 343 | return ret; 344 | } 345 | 346 | /* 347 | * Tree Depth First Search implementation 348 | * Implements iterative search using a Stack 349 | * Checks for a match before adding a node to Stack 350 | * 351 | * PARAMS 352 | * ------ 353 | * root: pointer to the root node pointer of a tree 354 | * val : value to search 355 | * stop: stop if val is found 356 | */ 357 | bool search_DFS(tree_pp root, int val, bool stop) 358 | { 359 | int ret = FALSE; 360 | tree_p node = NULL; 361 | stack_p stack = NULL; 362 | 363 | if (!root || !*root) { 364 | log(ERROR, "tree or root node is NULL.\n"); 365 | return FALSE; 366 | } 367 | 368 | /* Check for a match in root node */ 369 | node = *root; 370 | if (node->data == val) { 371 | log(INFO, "FOUND %d\n", val); 372 | 373 | if (stop) 374 | return TRUE; 375 | } 376 | 377 | stack = get_stack(); 378 | 379 | /* Add root node to Stack */ 380 | if (!push(stack, *root)) { 381 | log(ERROR, "push failed!\n"); 382 | destroy_stack(stack); 383 | return FALSE; 384 | } 385 | 386 | /* Process all valid nodes */ 387 | while (node) { 388 | log(INFO, "tracking...\n"); 389 | 390 | /* Match and add complete 391 | left subtree to Stack */ 392 | while (node->left) { 393 | if (node->left->data == val) { 394 | log(INFO, "FOUND %d\n", val); 395 | ret = TRUE; 396 | 397 | if (stop) { 398 | node = NULL; 399 | break; 400 | } 401 | } 402 | 403 | /* Add node to stack */ 404 | if (!push(stack, node->left)) { 405 | log(ERROR, "push failed!\n"); 406 | destroy_stack(stack); 407 | return FALSE; 408 | } 409 | 410 | node = node->left; 411 | } 412 | 413 | while ((node = pop(stack)) != NULL) { 414 | /* Process right child of node */ 415 | if (node->right) { 416 | if (node->right->data == val) { 417 | log(INFO, "FOUND %d\n", val); 418 | ret = TRUE; 419 | 420 | if (stop) { 421 | node = NULL; 422 | break; 423 | } 424 | } 425 | 426 | /* Add right child to Stack */ 427 | if (!push(stack, node->right)) { 428 | log(ERROR, "push failed!\n"); 429 | destroy_stack(stack); 430 | return FALSE; 431 | } 432 | 433 | node = node->right; 434 | /* Break inner loop if there's a right node */ 435 | break; 436 | } 437 | } 438 | } 439 | 440 | /* Report if no match was found */ 441 | if (!ret) 442 | log(INFO, "NOT FOUND\n"); 443 | 444 | destroy_stack(stack); 445 | 446 | return ret; 447 | } 448 | -------------------------------------------------------------------------------- /src/avl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * AVL Tree implementation 3 | * 4 | * Author: Arun Prakash Jana 5 | * Copyright (C) 2015 by Arun Prakash Jana 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with dslib. If not, see . 19 | */ 20 | 21 | #include "stack.h" 22 | #include "queue.h" 23 | #include "avl.h" 24 | 25 | /* 26 | * Struct to hold an AVL node and traversal 27 | * direction (left or right) to child node 28 | */ 29 | typedef struct { 30 | avl_p node; 31 | int direction; 32 | } nodedata, *nodedata_p; 33 | 34 | /* 35 | * Calculate the height of a node in AVL tree 36 | */ 37 | int height(avl_p node) 38 | { 39 | int lh, rh; 40 | 41 | if (!node) 42 | return 0; 43 | 44 | node->left == NULL ? lh = 0 : (lh = 1 + node->left->height); 45 | node->right == NULL ? rh = 0 : (rh = 1 + node->right->height); 46 | 47 | return (lh >= rh ? lh : rh); 48 | } 49 | 50 | /* 51 | * Calculate balance factor of subtree 52 | */ 53 | int BalanceFactor(avl_p node) 54 | { 55 | int lh, rh; 56 | 57 | if (!node) 58 | return 0; 59 | 60 | node->left == NULL ? lh = 0 : (lh = 1 + node->left->height); 61 | node->right == NULL ? rh = 0 : (rh = 1 + node->right->height); 62 | 63 | return (lh - rh); 64 | } 65 | 66 | /* 67 | * Rotate a node towards right 68 | */ 69 | avl_p RotateRight(avl_p node) 70 | { 71 | avl_p left_node = node->left; 72 | 73 | node->left = left_node->right; 74 | left_node->right = node; 75 | 76 | node->height = height(node); 77 | left_node->height = height(left_node); 78 | 79 | return left_node; 80 | } 81 | 82 | /* 83 | * Rotate a node towards left 84 | */ 85 | avl_p RotateLeft(avl_p node) 86 | { 87 | avl_p right_node = node->right; 88 | 89 | node->right = right_node->left; 90 | right_node->left = node; 91 | 92 | node->height = height(node); 93 | right_node->height = height(right_node); 94 | 95 | return right_node; 96 | } 97 | 98 | /* 99 | * Adjust a right right skewed subtree 100 | */ 101 | avl_p RightRight(avl_p node) 102 | { 103 | return RotateLeft(node); 104 | } 105 | 106 | /* 107 | * Adjust a left left skewed subtree 108 | */ 109 | avl_p LeftLeft(avl_p node) 110 | { 111 | return RotateRight(node); 112 | } 113 | 114 | /* 115 | * Adjust a left right skewed subtree 116 | */ 117 | avl_p LeftRight(avl_p node) 118 | { 119 | node->left = RotateLeft(node->left); 120 | return RotateRight(node); 121 | } 122 | 123 | /* 124 | * Adjust a right left skewed subtree 125 | */ 126 | avl_p RightLeft(avl_p node) 127 | { 128 | node->right = RotateRight(node->right); 129 | return RotateLeft(node); 130 | } 131 | 132 | /* 133 | * Rebalance subtree tmp based on balance factor & skew 134 | */ 135 | bool rebalance(stack_p stack, avl_pp head, avl_p tmp, int data) 136 | { 137 | nodedata_p p = NULL; 138 | int direction; 139 | avl_p parent = NULL; 140 | bool modified = TRUE; 141 | 142 | if (BalanceFactor(tmp) == -2) { /* Right subtree longer */ 143 | p = pop(stack); 144 | if (p) { 145 | parent = p->node; 146 | direction = p->direction; 147 | } 148 | 149 | if (data >= tmp->right->keyNode) { /* Right-right skewed subtree */ 150 | if (p) 151 | direction == RIGHT 152 | ? (parent->right = RightRight(tmp)) 153 | : (parent->left = RightRight(tmp)); 154 | else /* If p is NULL, this is the topmost node, update *head */ 155 | *head = RightRight(tmp); 156 | } else { /* Right-left skewed subtree */ 157 | if (p) 158 | direction == RIGHT 159 | ? (parent->right = RightLeft(tmp)) 160 | : (parent->left = RightLeft(tmp)); 161 | else 162 | *head = RightLeft(tmp); 163 | } 164 | } else if (BalanceFactor(tmp) == 2) { /* Left subtree longer */ 165 | p = pop(stack); 166 | if (p) { 167 | parent = p->node; 168 | direction = p->direction; 169 | } 170 | /* If p is NULL, this is the topmost node, update *head */ 171 | 172 | if (data < tmp->left->keyNode) { /* Left-left skewed subtree */ 173 | if (p) 174 | direction == RIGHT 175 | ? (parent->right = LeftLeft(tmp)) 176 | : (parent->left = LeftLeft(tmp)); 177 | else 178 | *head = LeftLeft(tmp); 179 | } else { /* Left-right skewed subtree */ 180 | if (p) 181 | direction == RIGHT 182 | ? (parent->right = LeftRight(tmp)) 183 | : (parent->left = LeftRight(tmp)); 184 | else 185 | *head = LeftRight(tmp); 186 | } 187 | } else 188 | modified = FALSE; 189 | 190 | if (p) 191 | free(p); 192 | 193 | tmp->height = height(tmp); 194 | 195 | return modified; 196 | } 197 | 198 | /* 199 | * Delete all nodes of an AVL tree 200 | */ 201 | int delete_avl_nodes(avl_p root) 202 | { 203 | int count = 0; 204 | 205 | if (!root) { 206 | log(ERROR, "root invalid.\n"); 207 | return 0; 208 | } 209 | 210 | if (root->left) 211 | count += delete_avl_nodes(root->left); 212 | 213 | if (root->right) 214 | count += delete_avl_nodes(root->right); 215 | 216 | free(root); 217 | root = NULL; 218 | 219 | return ++count; 220 | } 221 | 222 | 223 | 224 | /*=======================================================*/ 225 | /* Library exposed APIs start here */ 226 | /*=======================================================*/ 227 | 228 | /* 229 | * Generate an AVL tree iteratively from an array of integers 230 | */ 231 | avl_pp generate_avl(int *arr, int len) 232 | { 233 | 234 | avl_pp head = NULL; 235 | 236 | if (!arr || !len) { 237 | log(ERROR, "Invalid array.\n"); 238 | return NULL; 239 | } 240 | 241 | head = init_avl(); 242 | for (int i = 0; i < len; i++) { 243 | if (insert_avl_node(head, i, arr[i]) == FALSE) { 244 | log(ERROR, "Insertion failed.\n"); 245 | destroy_avl(head); 246 | return NULL; 247 | } 248 | } 249 | 250 | return head; 251 | } 252 | 253 | /* 254 | * Initialize an AVL tree with empty root node 255 | */ 256 | avl_pp init_avl(void) 257 | { 258 | avl_pp head = calloc(1, sizeof(avl_p)); 259 | *head = NULL; 260 | 261 | return head; 262 | } 263 | 264 | /* 265 | * Insert a new node into AVL tree 266 | */ 267 | bool insert_avl_node(avl_pp head, int key, int data) 268 | { 269 | avl_p root = NULL; 270 | nodedata_p p = NULL; 271 | nodedata_p n = NULL; 272 | bool modified; 273 | 274 | if (!head) { 275 | log(ERROR, "Initialize AVL tree first\n"); 276 | return FALSE; 277 | } 278 | 279 | root = *head; 280 | 281 | if (!root) { 282 | root = (avl_p) calloc(1, sizeof(avl_t)); 283 | root->keyNode = key; 284 | root->data = data; 285 | 286 | *head = root; 287 | 288 | return TRUE; 289 | } 290 | 291 | /* Stack to rebalance each subtree bottom-up after insertion */ 292 | stack_p stack = get_stack(); 293 | 294 | //until current node isn't Null 295 | while (root) { 296 | //if keyNod < of key to add, go left of tree 297 | if (key < root->keyNode) { 298 | //if left null, add node as left son 299 | if (!root->left) { 300 | /* Create an AVL node for new value */ 301 | root->left = calloc(1, sizeof(avl_t)); 302 | root->left->keyNode = key; 303 | root->left->data = data; 304 | root->height = height(root); 305 | 306 | modified = FALSE; 307 | 308 | /* Unwind stack & rebalance nodes (only once) */ 309 | while ((p = pop(stack)) != NULL) { 310 | /* One rebalance for one insertion */ 311 | if (!modified) 312 | modified = rebalance(stack, head, p->node, key); 313 | free(p); 314 | } 315 | break; 316 | } 317 | /* Push the parent node and traversal 318 | direction in stack as we traverse down */ 319 | n = malloc(sizeof(nodedata)); 320 | n->node = root; 321 | n->direction = LEFT; 322 | push(stack, n); 323 | 324 | /* Traverse further left */ 325 | root = root->left; 326 | } else { //key to add is >= then current key node 327 | //if right son null add son on it 328 | if (!root->right) { 329 | root->right = calloc(1, sizeof(avl_t)); 330 | root->right->keyNode = key; 331 | root->right->data = data; 332 | root->height = height(root); 333 | 334 | modified = FALSE; 335 | 336 | while ((p = pop(stack)) != NULL) { 337 | if (!modified) 338 | modified = rebalance(stack, head, p->node, key); 339 | free(p); 340 | } 341 | break; 342 | } 343 | 344 | n = malloc(sizeof(nodedata)); 345 | n->node = root; 346 | n->direction = RIGHT; 347 | push(stack, n); 348 | 349 | root = root->right; 350 | } 351 | } 352 | 353 | destroy_stack(stack); 354 | 355 | return TRUE; 356 | } 357 | 358 | /* 359 | * Delete a node from AVL tree 360 | * Recursive method 361 | */ 362 | bool delete_avl_node(avl_pp head, int key) 363 | { 364 | avl_p node; 365 | avl_p tmp; 366 | 367 | if (!head) { 368 | log(ERROR, "Initialize AVL tree first\n"); 369 | return FALSE; 370 | } 371 | 372 | node = *head; 373 | if (!node) { 374 | log(ERROR, "No nodes to delete\n"); 375 | return FALSE; 376 | } 377 | 378 | if (key > node->keyNode) { 379 | if (!node->right) 380 | return FALSE; 381 | 382 | if (delete_avl_node(&(node->right), key) == FALSE) 383 | return FALSE; 384 | 385 | if (BalanceFactor(node) == 2) { 386 | if (BalanceFactor(node->left) >= 0) 387 | node = LeftLeft(node); 388 | else 389 | node = LeftRight(node); 390 | } 391 | } else if (key < node->keyNode) { 392 | if (!node->left) 393 | return FALSE; 394 | 395 | if (delete_avl_node(&(node->left), key) == FALSE) 396 | return FALSE; 397 | 398 | if (BalanceFactor(node) == -2) { 399 | if (BalanceFactor(node->right) <= 0) 400 | node = RightRight(node); 401 | else 402 | node = RightLeft(node); 403 | } 404 | } else { /* Match found */ 405 | if (node->right) { /* Delete the inorder successor */ 406 | tmp = node->right; 407 | while (tmp->left) 408 | tmp = tmp->left; 409 | 410 | node->keyNode = tmp->keyNode; 411 | if (delete_avl_node(&(node->right), tmp->keyNode) == FALSE) 412 | return FALSE; 413 | 414 | if (BalanceFactor(node) == 2) { 415 | if (BalanceFactor(node->left) >= 0) 416 | node = LeftLeft(node); 417 | else 418 | node = LeftRight(node); 419 | } 420 | } else { 421 | *head = node->left; 422 | free(node); 423 | return TRUE; 424 | } 425 | } 426 | 427 | node->height = height(node); 428 | *head = node; 429 | return TRUE; 430 | } 431 | 432 | /* 433 | * Destroy an AVL tree 434 | */ 435 | int destroy_avl(avl_pp head) 436 | { 437 | int count = 0; 438 | 439 | if (!head) { 440 | log(ERROR, "head invalid.\n"); 441 | return -1; 442 | } 443 | 444 | count = delete_avl_nodes(*head); 445 | 446 | free(head); 447 | head = NULL; 448 | 449 | return count; 450 | } 451 | 452 | /* 453 | * Print the values in an AVL tree in preorder 454 | */ 455 | int print_avl(avl_p root, avl_p parent) 456 | { 457 | int count = 0; 458 | 459 | if (!root) { 460 | log(ERROR, "root invalid.\n"); 461 | return -1; 462 | } 463 | 464 | ++count; 465 | 466 | /* Print key:data values in the node */ 467 | log(INFO, "key:data=%6d:%d, parent key=%6d\n", root->keyNode, root->data, parent->keyNode); 468 | 469 | if (root->left) { 470 | log(INFO, "LEFT.\n"); 471 | count += print_avl(root->left, root); 472 | } 473 | 474 | if (root->right) { 475 | log(INFO, "RIGHT.\n"); 476 | count += print_avl(root->right, root); 477 | } 478 | 479 | return count; 480 | } 481 | 482 | /* 483 | * AVL Tree Breadth First Search implementation 484 | * Implements iterative search using a Queue 485 | * Checks for a match before adding a node to Queue 486 | * 487 | * PARAMS 488 | * ------ 489 | * root: pointer to the root node pointer of an AVL tree 490 | * val : value to search 491 | * stop: TRUE: stop if Key is found and return val. 492 | * FALSE: continue visiting of tree, print debug info and return the val of the last key. 493 | */ 494 | 495 | int search_BFS_avl(avl_pp root, int key, bool stop) 496 | { 497 | //return -1 is error 498 | //return -2 is not Found 499 | avl_p node = NULL; 500 | queue_p queue = NULL; 501 | int ret = -2; //start with no found 502 | 503 | if (!root || !*root) { 504 | log(ERROR, "avl tree or root node is NULL!\n"); 505 | return -2; //because avl is empty so key is not found 506 | } 507 | 508 | /* Check for a match in root node */ 509 | node = *root; 510 | if (node->keyNode == key) { 511 | if (!stop) 512 | log(INFO, "FOUND %d\n", key); 513 | if (stop) 514 | ret = node->data; 515 | else 516 | ret = node->data; 517 | } 518 | queue = get_queue(); 519 | 520 | /* Add root node to Queue */ 521 | if (!enqueue(queue, *root)) { 522 | log(ERROR, "enqueue failed!\n"); 523 | destroy_queue(queue); 524 | return -1; 525 | } 526 | 527 | /* Loop through all nodes in the Queue */ 528 | while ((node = dequeue(queue)) != NULL) { 529 | if (!stop) 530 | log(INFO, "tracking...\n"); 531 | /* Process left child of node */ 532 | if (node->left) { 533 | if (node->left->keyNode == key) { 534 | if (stop) 535 | ret = node->left->data; 536 | else { 537 | log(INFO, "FOUND %d\n", key); 538 | ret = node->right->data; 539 | } 540 | break; 541 | } 542 | 543 | /* Add left child to Queue */ 544 | if (!enqueue(queue, node->left)) { 545 | log(ERROR, "enqueue failed!\n"); 546 | destroy_queue(queue); 547 | return -1; 548 | } 549 | } 550 | 551 | /* Process right child of node */ 552 | if (node->right) { 553 | if (node->right->keyNode == key) { 554 | if (stop) 555 | ret = node->right->data; 556 | else { 557 | log(INFO, "FOUND %d\n", key); 558 | ret = node->left->data; 559 | } 560 | break; 561 | } 562 | 563 | /* Add right child to Queue */ 564 | if (!enqueue(queue, node->right)) { 565 | log(ERROR, "enqueue failed!\n"); 566 | destroy_queue(queue); 567 | return -1; 568 | } 569 | } 570 | } 571 | 572 | /* Report if no match was found */ 573 | 574 | destroy_queue(queue); 575 | 576 | return ret; 577 | } 578 | 579 | /*=======================================================*/ 580 | /* Library ThreadSafe APIs start here */ 581 | /*=======================================================*/ 582 | 583 | /* 584 | * Generate an AVL tree iteratively from an array of integers 585 | */ 586 | avl_pp_S generate_avl_S(int *arr, int len) 587 | { 588 | int i = 0; 589 | avl_pp_S head; 590 | 591 | if (!arr || !len) { 592 | log(ERROR, "Invalid array.\n"); 593 | head.avlRoot = NULL; 594 | return head; 595 | } 596 | 597 | head = init_avl_S(); 598 | 599 | for (; i < len; i++) { 600 | if (insert_avl_node(head.avlRoot, i, arr[i]) == FALSE) { 601 | log(ERROR, "Insertion failed.\n"); 602 | destroy_avl(head.avlRoot); 603 | head.avlRoot = NULL; 604 | return head; 605 | } 606 | } 607 | 608 | return head; 609 | } 610 | 611 | avl_pp_S init_avl_S(void) 612 | { 613 | avl_pp_S head; 614 | 615 | head.semId = semInit(); 616 | if (head.semId == -1) { 617 | perror("Sem Setup failed"); 618 | head.avlRoot = NULL; 619 | return head; 620 | } 621 | 622 | head.avlRoot = calloc(1, sizeof(avl_p)); 623 | *head.avlRoot = NULL; 624 | 625 | return head; 626 | } 627 | 628 | bool insert_avl_node_S(avl_pp_S head, int key, int data) 629 | { 630 | bool ret; 631 | 632 | lockWriteSem(head.semId); 633 | ret = insert_avl_node(head.avlRoot, key, data); 634 | unlockWriteSem(head.semId); 635 | return ret; 636 | } 637 | 638 | bool delete_avl_node_S(avl_pp_S head, int key) 639 | { 640 | bool ret; 641 | 642 | lockWriteSem(head.semId); 643 | ret = delete_avl_node(head.avlRoot, key); 644 | unlockWriteSem(head.semId); 645 | return ret; 646 | } 647 | 648 | int search_BFS_avl_S(avl_pp_S root, int key, bool stop) 649 | { 650 | int ret; 651 | 652 | lockReadSem(root.semId); 653 | ret = search_BFS_avl(root.avlRoot, key, stop); 654 | unlockReadSem(root.semId); 655 | return ret; 656 | } 657 | 658 | int print_avl_S(avl_pp_S root) 659 | { 660 | int ret; 661 | 662 | lockReadSem(root.semId); 663 | ret = print_avl(*root.avlRoot, *root.avlRoot); 664 | unlockReadSem(root.semId); 665 | return ret; 666 | } 667 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | --------------------------------------------------------------------------------