repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
pniekamp/datum-studio
include/font.h
#include "../src/plugins/font/font.h"
pniekamp/datum-studio
src/plugins/content/folderview.h
<filename>src/plugins/content/folderview.h<gh_stars>1-10 // // Folder View // // // Copyright (C) 2016 <NAME> // #pragma once #include <QTreeWidget> //-------------------------- FolderView ------------------------------------- //--------------------------------------------------------------------------- class FolderView : public QTreeWidget { Q_OBJECT public: FolderView(QWidget *parent = 0); QSize sizeHint() const { return QSize(190, 256); } void set_base(QString const &basepath); public: QString selected_path() const; public slots: void select_path(QString const &path); void trigger_rename(QTreeWidgetItem *item); void update(QString const &path); void refresh(); signals: void selection_changed(QString const &path); void item_renamed(QString const &src, QString const &dst); protected: void itemSelectionChanged(); void commitData(QWidget *editor); QStringList mimeTypes() const; QMimeData *mimeData(QList<QTreeWidgetItem *> const items) const; Qt::DropActions supportedDropActions() const; void dropEvent(QDropEvent *event); private: QString m_basepath; };
haomingzhi/HelloTest
Example/HelloTest/JYAppDelegate.h
// // JYAppDelegate.h // HelloTest // // Created by HadesSura on 06/19/2020. // Copyright (c) 2020 HadesSura. All rights reserved. // @import UIKit; @interface JYAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
haomingzhi/HelloTest
HelloTest/Classes/NewMMM.h
// // NewMMM.h // FBSnapshotTestCase // // Created by 暖色科技 on 2020/7/3. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NewMMM : NSObject @end NS_ASSUME_NONNULL_END
haomingzhi/HelloTest
Example/HelloTest/JYViewController.h
<gh_stars>0 // // JYViewController.h // HelloTest // // Created by HadesSura on 06/19/2020. // Copyright (c) 2020 HadesSura. All rights reserved. // @import UIKit; @interface JYViewController : UIViewController @end
Steve132/rs_led
m_led/LedStripRS.h
<reponame>Steve132/rs_led #ifndef LedStripRS_H #define LedStripRS_H #include <avr/pgmspace.h> // ******** DEBUG ==== should auto config to adapt different mother board ********* //#define DATA_1 (PORTF |= 0X01) // DATA 1 // for ATMEGA //#define DATA_0 (PORTF &= 0XFE) // DATA 0 // for ATMEGA //#define STRIP_PINOUT DDRF=0xFF // for ATMEGA #define DATA_1 (PORTC |= 0X01) // DEFINE a value for DATA as 1 // for UNO #define DATA_0 (PORTC &= 0XFE) // DEFINE a value for DATA 0 // for UNO #define STRIP_PINOUT (DDRC=0x3F) // DEFINE PORTC as OUTPUT // for UNO (change pins 0-5; leave PORTC 6 & 7 alone) #define NOP1 "nop\n\t" #define NOP2 NOP1 NOP1 #define NOP4 NOP2 NOP2 #define NOP8 NOP4 NOP4 #define NOP16 NOP8 NOP8 #define LSPC 2 #define LSPB 1 #define LSPD 0 template<int cs, int spin> struct _static_pin_part2 { inline static void set() __attribute__((always_inline)); inline static void clear() __attribute__((always_inline)); }; template<int spin> struct _static_pin_part2<LSPD,spin> { inline static void set() __attribute__((always_inline)) { PORTD |= (0x1 << spin); } inline static void clear() __attribute__((always_inline)) { PORTD &= ~(0x1 << spin); } }; template<int spin> struct _static_pin_part2<LSPB,spin> { inline static void set() __attribute__((always_inline)) { PORTB |= (0x1 << (spin-8)); } inline static void clear() __attribute__((always_inline)) { PORTB &= ~(0x1 << (spin-8)); } }; template<int spin> struct _static_pin_part2<LSPC,spin> { inline static void set() __attribute__((always_inline)) { PORTC |= (0x1 << (spin-14)); } inline static void clear() __attribute__((always_inline)) { PORTC &= ~(0x1 << (spin-14)); } }; template<int spin> struct _static_pin { typedef _static_pin_part2<(spin < 8) ? ( LSPD ) : ( (spin < 14) ? LSPB : LSPC ),spin> _part2; inline static void set() __attribute__((always_inline)) { _part2::set(); } inline static void clear() __attribute__((always_inline)) { _part2::clear(); } }; class BaseLedStripRS { public: virtual void send_color(uint32_t c); virtual void send_pattern(const uint32_t data[]); virtual void setup(); virtual void reset(); }; template<int spin,int length=10> class LedStripRS: public BaseLedStripRS { private: void send_single(uint32_t data) { int i; unsigned long j=0x800000; for (i=0;i<24;i++) { if (data & j) { //digitalWrite(pin,HIGH); _static_pin<spin>::set(); __asm__(NOP16 NOP8); //digitalWrite(pin,LOW); _static_pin<spin>::clear(); } else { //digitalWrite(pin,HIGH); _static_pin<spin>::set(); __asm__(NOP8 NOP1); //digitalWrite(pin,LOW); _static_pin<spin>::clear(); /*----------------------------*/ __asm__(NOP2 NOP1); /*----------------------------*/ } j>>=1; } } public: LedStripRS() {} void setup() { pinMode(spin, OUTPUT); // sets the digital pin as output reset(); } void send_pattern(const uint32_t data[]) { int j=0; noInterrupts(); // Turn OFF Interupts for more precise Pulse Timing for (j=0;j<length;j++) { uint32_t c=pgm_read_dword_near(&data[j]); send_single(c); } interrupts(); // Turn ON Interrupts after data is sent } void send_color(uint32_t c) { int j=0; noInterrupts(); // Turn OFF Interupts for more precise Pulse Timing for (j=0;j<length;j++) { send_single(c); } interrupts(); // Turn ON Interrupts after data is sent } void reset() { _static_pin<spin>::clear(); delayMicroseconds(20); } }; uint32_t brighten(uint32_t color,uint8_t brightness); uint32_t slowdown(uint32_t delay,uint32_t sd); //fixed-point, 10 bit fraction. #endif //LedStripRS
adtac/hollow-heap
benchmark/wrappers/wrappers.h
#ifndef _WRAPPERS_H_ #define _WRAPPERS_H_ #include "fibonacci_heap.h" #include "pairing_heap.h" #include "relaxed_heap.h" #include "hollow_heap.h" #endif // _WRAPPERS_H_
adtac/hollow-heap
benchmark/graphs.h
<gh_stars>1-10 #ifndef _GRAPHS_H_ #define _GRAPHS_H_ #include <vector> #include <utility> class Node { public: std::vector<std::pair<int, int>> out_edges; int label; Node(int _label) { label = _label; } void add_edge(int _u, int _w) { out_edges.push_back(std::make_pair(_u, _w)); } }; class Graph { public: int N; long long int M; std::vector<Node> vertices; Graph(int _N, long long int _M) { N = _N; M = _M; for (int i = 0; i < N; i++) { vertices.push_back(Node(i)); } } void generate_random(int seed) { long long int edges_left = M; long long int max_edges = N; max_edges = (max_edges * (max_edges-1)) / 2; double threshold_p = double(edges_left) / double(max_edges); srand(seed); for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { double p = (rand() % 1000000) / 1000000.00; if (p < threshold_p) { int w = 1 + (rand()%100); vertices[i].add_edge(j, w); vertices[j].add_edge(i, w); } } } } }; #endif // _GRAPH_H_
adtac/hollow-heap
benchmark/sort.h
<gh_stars>1-10 #ifndef _SORT_H_ #define _SORT_H_ #include <vector> template<class Heap> long long int Benchmark<Heap>::sort(int N, int* nums) { log("running sort\n"); std::vector<int> numbers; std::vector<int> results; log("generating numbers\n"); for (int i = 0; i < N; i++) numbers.push_back(nums[i]); log("inserting and retrieving numbers\n"); long long int pre_insert = elapsed(); Heap h; for (int i = 0; i < N; i++) h.push(numbers[i], numbers[i]); while (!h.empty()) { results.push_back(*h.find_min()); h.delete_min(); } long long int post_retrieval = elapsed(); log("elapsed: %lld us\n", post_retrieval - pre_insert); log("sorting using STL\n"); std::sort(numbers.begin(), numbers.end()); log("verifying\n"); if (numbers.size() != results.size()) { log("incorrect: numbers.size() != results.size() (%d != %d)\n", numbers.size(), results.size()); return -1; } else { for (int i = 0; i < results.size(); i++) { if (numbers[i] != results[i]) { log("incorrect: numbers[%d] != results[%d] (%d != %d)\n", i, i, numbers[i], results[i]); return -1; } } log("correct!\n", heap_name); return post_retrieval - pre_insert; } } #endif // _SORT_H_
adtac/hollow-heap
benchmark/wrappers/compare_node.h
<reponame>adtac/hollow-heap #ifndef _COMPARE_NODE_H_ #define _COMPARE_NODE_H_ #include <utility> /** * A comparison class that's used uniformly by Boost's heap data structures * to define the ordering between two keys of type pair<K, I>. */ template<class K, class I> struct compare_node { bool operator()(const std::pair<K, I> n1, const std::pair<K, I> n2) const { return n1.first > n2.first; } }; #endif // _COMPARE_NODE_H_
adtac/hollow-heap
benchmark/dijkstra.h
<reponame>adtac/hollow-heap #ifndef _DIJKSTRA_H_ #define _DIJKSTRA_H_ #include <cmath> #include <vector> #include <climits> #include <utility> #include "graphs.h" template<class Heap> long long Benchmark<Heap>::dijkstra(Graph* g) { log("running dijkstra\n"); std::vector<int> in_tree(g->N, 0); std::vector<int> dist(g->N, 1e9); std::vector<int> parent(g->N, -1); std::vector<typename Heap::reference> node_map(g->N); in_tree[0] = 1; dist[0] = 0; log("computing the shortest path tree\n"); Heap h; long long int pre_compute = elapsed(); node_map[0] = h.push(0, 0); for (int i = 1; i < g->N; i++) node_map[i] = h.push(1e9, i); while (!h.empty()) { int u = *h.find_min(); int d = dist[u]; h.delete_min(); for (int i = 0; i < g->vertices[u].out_edges.size(); i++) { std::pair<int, int> vw = g->vertices[u].out_edges[i]; int v = vw.first; int w = vw.second; if (in_tree[v] == 0 && d+w < dist[v]) { dist[v] = d+w; in_tree[v] = 1; node_map[v] = h.decrease_key(node_map[v], dist[v]); parent[v] = u; } } } long long int post_compute = elapsed(); log("elapsed = %lld us\n", post_compute - pre_compute); return post_compute - pre_compute; } #endif // _DIJKSTRA_H_
adtac/hollow-heap
benchmark/wrappers/fibonacci_heap.h
#ifndef _FIBONACCI_HEAP_H_ #define _FIBONACCI_HEAP_H_ #include <boost/heap/fibonacci_heap.hpp> #include "compare_node.h" template<class K, class I> class WrapperBoostFibonacciHeap { boost::heap::fibonacci_heap<std::pair<K, I>, boost::heap::compare<compare_node<K, I>>> h; public: typedef typename boost::heap::fibonacci_heap<std::pair<K, I>, boost::heap::compare<compare_node<K, I>>>::handle_type reference; reference push(K key, I item) { return h.push(std::make_pair(key, item)); } void delete_min() { h.pop(); } const I* find_min() { return &(h.top().second); } bool empty() { return h.empty(); } reference decrease_key(reference u, K& new_key) { (*u).first = new_key; h.decrease(u); return u; } }; #endif // _FIBONACCI_HEAP_H_
adtac/hollow-heap
benchmark/assorted.h
<reponame>adtac/hollow-heap #ifndef _ASSORTED_H_ #define _ASSORTED_H_ #include <algorithm> #include <utility> #include <vector> #include <map> #include <climits> template<class Heap> long long Benchmark<Heap>::assorted(int N, int* nums, int* idxs, int* decs) { log("running assorted\n"); std::vector<std::pair<int, int>> ns(N); std::vector<std::pair<int, typename Heap::reference>> m(N); log("beginning %d inserts, %d decrease-keys and %d delete-mins\n", N, 2*N, N); long long int pre_push = elapsed(); Heap h; long long int total_time = 0; for (int i = 0; i < N; i++) { int x = nums[i]; m[i] = std::make_pair(x, h.push(x, i)); ns[i] = std::make_pair(x, i); } for (int i = 0; i < 2*N; i++) { int idx = idxs[i]; int x = m[idx].first; x -= decs[i]; if (i == 5) continue; ns[idx].first = x; m[idx].first = x; m[idx].second = h.decrease_key(m[idx].second, x); } total_time += elapsed() - pre_push; std::sort(ns.begin(), ns.end()); std::vector<int> end_val(N); for (int i = 0; i < N; i++) end_val[ns[i].second] = ns[i].first; long long int pre_retrieval = elapsed(); int correct = 1; int prev = INT_MIN; for (int i = 0; i < N; i++) { int* res = (int*) h.find_min(); if (end_val[*res] > prev) correct = 1; prev = end_val[*res]; h.delete_min(); } total_time += elapsed() - pre_retrieval; log("elapsed = %lld us\n", total_time); if (correct) log("correct!\n"); else log("incorrect!\n"); return total_time; } #endif // _ASSORTED_H_
adtac/hollow-heap
benchmark/prim.h
#ifndef _PRIM_H_ #define _PRIM_H_ #include <cmath> #include <vector> #include <climits> #include <utility> #include "graphs.h" template<class Heap> long long Benchmark<Heap>::prim(Graph* g) { log("running prim\n"); std::vector<int> in_mst(g->N, 0); std::vector<int> weight_in(g->N, -1); std::vector<int> d(g->N, 1e9); std::vector<typename Heap::reference> node_map(g->N); long long int total_weight = 0; d[0] = 0; log("computing the shortest path tree\n"); long long int pre_compute = elapsed(); Heap h; node_map[0] = h.push(0, 0); weight_in[0] = 0; for (int i = 1; i < g->N; i++) node_map[i] = h.push(INT_MAX, i); while (!h.empty()) { int u = *h.find_min(); if (weight_in[u] == -1) break; in_mst[u] = 1; total_weight += weight_in[u]; h.delete_min(); for (int i = 0; i < g->vertices[u].out_edges.size(); i++) { std::pair<int, int> vw = g->vertices[u].out_edges[i]; int v = vw.first; int w = vw.second; if (in_mst[v] == 0 && w < d[v]) { d[v] = w; node_map[v] = h.decrease_key(node_map[v], d[v]); weight_in[v] = w; } } } long long int post_compute = elapsed(); log("elapsed = %lld us\n", post_compute - pre_compute); log("computed MST weight = %lld\n", total_weight); return post_compute - pre_compute; } #endif // _PRIM_H_
adtac/hollow-heap
benchmark/wrappers/relaxed_heap.h
#ifndef _RELAXED_HEAP_H_ #define _RELAXED_HEAP_H_ #include <boost/pending/relaxed_heap.hpp> std::vector<std::pair<int, int>> vals; template<class K, class I> class relaxed_compare { public: bool operator()(int a, int b) const { return vals[a].first < vals[b].first; } }; template<class K, class I> class WrapperBoostRelaxedHeap { boost::relaxed_heap<int, relaxed_compare<K, I>> h; int size; public: typedef int reference; WrapperBoostRelaxedHeap() : h(1000000) { size = 0; } reference push(K key, I item) { vals.resize(size+1); vals[size] = std::make_pair(key, item); h.push(size); size++; return size-1; } void delete_min() { h.remove(h.top()); } const I* find_min() { return &vals[h.top()].second; } bool empty() { return h.empty(); } reference decrease_key(reference u, K& new_key) { vals[u].first = new_key; h.update(u); return u; } }; #endif // _RELAXED_HEAP_H_
adtac/hollow-heap
benchmark/argument.h
<reponame>adtac/hollow-heap<gh_stars>1-10 #ifndef _ARGUMENT_H_ #define _ARGUMENT_H_ #include <cmath> #include "graphs.h" typedef struct { int N; int* sort_ints; int* assorted_ints; int* assorted_idxs; int* assorted_decs; Graph* sparse_graph; Graph* dense_graph; Graph* nyc_graph; Graph* bay_graph; int* comp_ints; int* freq_table; } argument; argument* init_args(int N, int seed) { argument* a = new argument; a->N = N; if (N == 0) { char* cities[] = {"nyc.input", "bay.input", NULL}; Graph** g[] = {&a->nyc_graph, &a->bay_graph, NULL}; int j = 0; char* line = (char*) malloc(100); while (cities[j] != NULL) { FILE* city = fopen(cities[j], "r"); int cn, cm; if (city == NULL) { fprintf(stderr, "cannot find %s", cities[j]); exit(1); } while (fgets(line, 100, city)) { if (*line == 'p') { sscanf(line, "p sp %d %d", &cn, &cm); break; } } *g[j] = new Graph(cn, cm); while (fgets(line, 100, city)) { if (*line == 'a') { int f, t, d; sscanf(line, "a %d %d %d", &f, &t, &d); (*g[j])->vertices[f-1].add_edge(t-1, d); } } j++; } free(line); } else { srand(seed); fprintf(stderr, "generating sort_ints...\n"); a->sort_ints = new int[N]; for (int i = 0; i < N; i++) a->sort_ints[i] = rand() % N; srand(seed); fprintf(stderr, "generating assorted_ints...\n"); a->assorted_ints = new int[N]; for (int i = 0; i < N; i++) a->assorted_ints[i] = rand() % N; fprintf(stderr, "generating assorted_idxs, assorted_decs...\n"); a->assorted_idxs = new int[2*N]; a->assorted_decs = new int[2*N]; for (int i = 0; i < 2*N; i++) { a->assorted_idxs[i] = rand() % N; a->assorted_decs[i] = rand()%100 + 1; } srand(seed); int V = N / 8; fprintf(stderr, "generating sparse_graph...\n"); a->sparse_graph = new Graph(V, V * log(V)); a->sparse_graph->generate_random(seed); fprintf(stderr, "generating dense_graph...\n"); a->dense_graph = new Graph(V, pow(V, 1.75)); a->dense_graph->generate_random(seed); srand(seed); int num_elems = N * sqrt(N); fprintf(stderr, "generating comp_ints, freq_table...\n"); a->comp_ints = new int[num_elems]; a->freq_table = new int[N]; for (int i = 0; i < N; i++) a->freq_table[i] = 0; for (int i = 0; i < num_elems; i++) { a->comp_ints[i] = rand() % N; a->freq_table[a->comp_ints[i]]++; } } return a; } #endif // _ARGUMENT_H_
adtac/hollow-heap
benchmark/compression.h
#ifndef _COMPRESSION_H_ #define _COMPRESSION_H_ #include <cmath> #include <utility> #include <vector> typedef struct { int freq; int val; int left; int right; } huffman_node; template<class Heap> long long Benchmark<Heap>::compression(int N, int* freq_table) { log("running compression\n"); log("computing the Huffman tree\n"); long long int pre_compute = elapsed(); Heap h; std::vector<huffman_node> nodes; int heap_size = 0; for (int i = 0; i < N; i++) { if (freq_table[i] > 0) { nodes.push_back(huffman_node {freq_table[i], i, -1, -1}); h.push(freq_table[i], nodes.size()-1); heap_size++; } } while (heap_size > 1) { int l1 = *h.find_min(); h.delete_min(); int l2 = *h.find_min(); h.delete_min(); nodes.push_back(huffman_node {nodes[l1].freq+nodes[l2].freq, -1, l1, l2}); h.push(nodes[l1].freq+nodes[l2].freq, nodes.size()-1); heap_size--; } long long int post_compute = elapsed(); log("elapsed = %lld us\n", post_compute - pre_compute); return post_compute - pre_compute; } #endif
adtac/hollow-heap
benchmark/benchmark.h
<gh_stars>1-10 #ifndef _BENCHMARK_H_ #define _BENCHMARK_H_ #include <chrono> #include <cstdarg> #include <cstdio> #include <algorithm> #include <vector> #include <cstdlib> #include <map> #include <utility> #include "graphs.h" #include "argument.h" #define SORT 0x1 #define ASSORTED 0x2 #define DIJKSTRA 0x4 #define PRIM 0x8 #define COMPRESSION 0x10 #define ROADS 0x20 template<class Heap> class Benchmark { std::chrono::high_resolution_clock::time_point start; char* heap_name; public: Benchmark(char* _heap_name) { heap_name = _heap_name; start = std::chrono::high_resolution_clock::now(); } long long int elapsed() { auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void log(const char *format, ...) { va_list args; va_start(args, format); fprintf(stderr, "[%9lld] [%-5s] ", elapsed(), heap_name); vfprintf(stderr, format, args); va_end(args); } long long sort(int, int*); long long assorted(int, int*, int*, int*); long long dijkstra(Graph*); long long prim(Graph*); long long compression(int, int*); void run(int benchmarks, argument* args) { if (benchmarks & SORT) { printf("%s_sort=%lld ", heap_name, sort(args->N, args->sort_ints)); } if (benchmarks & ASSORTED) printf("%s_assorted=%lld ", heap_name, assorted(args->N, args->assorted_ints, args->assorted_idxs, args->assorted_decs)); if (benchmarks & DIJKSTRA) { printf("%s_dijkstra_sparse=%lld ", heap_name, dijkstra(args->sparse_graph)); printf("%s_dijkstra_dense=%lld ", heap_name, dijkstra(args->dense_graph)); } if (benchmarks & PRIM) { printf("%s_prim_sparse=%lld ", heap_name, prim(args->sparse_graph)); printf("%s_prim_dense=%lld ", heap_name, prim(args->dense_graph)); } if (benchmarks & COMPRESSION) { printf("%s_compression=%lld ", heap_name, compression(args->N, args->freq_table)); } if (benchmarks & ROADS) { printf("%s_dijkstra_nyc=%lld ", heap_name, dijkstra(args->nyc_graph)); printf("%s_prim_nyc=%lld ", heap_name, prim(args->nyc_graph)); printf("%s_dijkstra_bay=%lld ", heap_name, dijkstra(args->bay_graph)); printf("%s_prim_bay=%lld ", heap_name, prim(args->bay_graph)); } } }; #include "sort.h" #include "assorted.h" #include "dijkstra.h" #include "prim.h" #include "compression.h" #endif // _BENCHMARK_H_
JackDinsmore/SimplePlots
simpleplot.h
<filename>simpleplot.h #pragma once #include "simpleplot/plots/hist.h" #include "simpleplot/plots/line.h" #include "simpleplot/plots/series.h" #include "simpleplot/canvas.h"
JackDinsmore/SimplePlots
simpleplot/plots/series.h
<gh_stars>0 #pragma once #include "plot.h" #include "../axis.h" namespace SimplePlot::Series { template<typename X, typename Y> class Series : public SimplePlot::Plot::Plot { public: Series(X skip, Y* data, int sizeData, int style, std::wstring name); ~Series(); private: void getAxisLimits(float* axisLimits) const override; void draw(HDC hdc, float const* axisLimits, POINT const* drawSpace) const override; void isolateData() override; void deleteData() override; X skip; Y* data; int sizeData; }; } namespace SimplePlot { template<typename X, typename Y> extern PLOT_ID makeSeries(X skip, Y* data, int sizeData, int style = 0, std::wstring name = L""); }
JackDinsmore/SimplePlots
simpleplot/plots/hist.h
#pragma once #include "plot.h" #include "../axis.h" namespace SimplePlot::Hist { template<typename Y> class Hist : public SimplePlot::Plot::Plot { public: Hist(Y* data, int sizeData, int numBins, Y minBin, Y maxBin, int style, std::wstring name, bool normal = false); Hist(Y* data, int sizeData, Y* leftBins_, int numBins, int style, std::wstring name, bool normal = false); ~Hist(); private: void getAxisLimits(float* axisLimits) const override; void draw(HDC hdc, float const* axisLimits, POINT const* drawSpace) const override; void isolateData() override; void deleteData() override; Y* data; int sizeData; Y* leftBins = nullptr; Y minBin; Y maxBin; int numBins; bool normal; }; } namespace SimplePlot { template<typename Y> extern PLOT_ID makeHist(Y* data, int sizeData, int numBins, Y minBin, Y maxBin, int style = 0, std::wstring name = L"", bool normal = false); template<typename Y> extern PLOT_ID makeHist(Y* data, int sizeData, Y* leftBins, int numBins, int style = 0, std::wstring name = L"", bool normal = false); }
JackDinsmore/SimplePlots
simpleplot/plots/plot.h
<reponame>JackDinsmore/SimplePlots #pragma once #include <string> #include <windows.h> #include "../standard.h" #include "../colors.h" namespace SimplePlot { namespace Plot { class Plot { public: Plot(PLOT_TYPE plotType, AXIS_TYPE axisType, int style, std::wstring name); Plot(const Plot&) = delete; Plot(Plot&&) = delete; Plot& operator=(Plot const&) = delete; Plot& operator=(Plot&&) = delete; virtual void isolateData() = 0; virtual void deleteData() = 0; virtual void getAxisLimits(float* axisLimits) const = 0; virtual void draw(HDC hdc, float const* axisLimits, POINT const* drawSpace) const = 0; void drawLegend(HDC hdc, RECT legendRect); void getGeneralAxisLimits(float* axisLimits, bool set) const; PLOT_ID id = SP_NULL_PLOT; CANVAS_ID canvas = SP_NULL_CANVAS; AXIS_TYPE axisType; PLOT_TYPE plotType; int numAxes; float* setAxisLimits; bool* isSetAxisLimits; std::wstring name; protected: SimplePlot::Style::Style style; private: inline static PLOT_ID maxID = 0; }; } void deletePlot(PLOT_ID plot); void registerPlot(PLOT_ID, Plot::Plot* plt, PLOT_TYPE plotType); AXIS_TYPE getPlotAxisType(PLOT_ID id); PLOT_TYPE getPlotType(PLOT_ID id); void getPlotAxisLimits(PLOT_ID id, float* axisLimits, bool set); void isolatePlotData(PLOT_ID id); void deletePlotData(PLOT_ID id); void drawPlot(PLOT_ID id, HDC hdc, float const* axisLimits, POINT const* drawSpace); void drawPlotLegend(PLOT_ID id, HDC hdc, RECT legendRect); void associatePlot(PLOT_ID plotID, CANVAS_ID canvasID); void disassociatePlot(PLOT_ID plotID); CANVAS_ID getPlotCanvas(PLOT_ID plotID); void setPlotAxisLimits(PLOT_ID id, int axisNum, float lowLimit, float highLimit); void setPlotLowerAxisLimit(PLOT_ID id, int axisNum, float lowLimit); void setPlotUpperAxisLimit(PLOT_ID id, int axisNum, float highLimit); std::wstring getPlotName(PLOT_ID id); }
JackDinsmore/SimplePlots
simpleplot/stats.h
#pragma once #include <string> namespace SimplePlot::Stats { template<typename T> T minValue(T* p, int size); template<typename T> T maxValue(T* p, int size); template<typename T> int binFindLeft(T* v, int size, T data, int start = 0); template<typename T> std::wstring round(T f, int numDigs); }
JackDinsmore/SimplePlots
simpleplot/plots/line.h
#pragma once #include "plot.h" #include "../axis.h" namespace SimplePlot::Line { template<typename X, typename Y> class Line : public SimplePlot::Plot::Plot { public: Line(X* xData, Y* yData, int sizeData, int style, std::wstring name); ~Line(); private: void getAxisLimits(float* axisLimits) const override; void draw(HDC hdc, float const* axisLimits, POINT const* drawSpace) const override; void isolateData() override; void deleteData() override; X* xData; Y* yData; int sizeData; }; } namespace SimplePlot { template<typename X, typename Y> extern PLOT_ID makeLine(X* x, Y* y, int sizeData, int style = 0, std::wstring name = L""); }
JackDinsmore/SimplePlots
simpleplot/standard.h
#pragma once #define SP_DEFAULT_WIDTH 800 #define SP_DEFAULT_HEIGHT 600 #define SP_DEFAULT_FRAMERATE 5 #define SP_DYNAMIC SP_DEFAULT_FRAMERATE #define SP_STATIC -1 #define SP_BORDER_WIDTH 80 #define SP_TICK_LENGTH 6 #define SP_NULL_PLOT -1 #define SP_NULL_CANVAS -1 #define SP_X_AXIS 0 #define SP_Y_AXIS 1 #define SP_Z_AXIS 2 #define SP_MAX_ASPECT 5 namespace SimplePlot { typedef int PLOT_ID; typedef int CANVAS_ID; enum class PLOT_TYPE { // Ordered in terms of depth: the lowest numbers are drawn first. SP_NULL_PLOT_TYPE, LINE, SERIES, HISTOGRAM, }; enum class AXIS_TYPE { NULL_AXES, CART_2D, CART_3D, SPECIAL, }; }
JackDinsmore/SimplePlots
simpleplot/wndProc.h
#pragma once #include "standard.h" #include <mutex> #include <map> #include <windows.h> namespace SimplePlot { inline extern std::map<HWND, HBITMAP> hwndToBitmap = std::map<HWND, HBITMAP>(); inline extern std::mutex hwndToBitmapMutex = std::mutex(); inline extern std::map<HWND, bool> terminateCanvas = std::map<HWND, bool>(); inline extern std::mutex terminateCanvasMutex = std::mutex(); namespace wndProc { LRESULT CALLBACK wndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); } }
JackDinsmore/SimplePlots
simpleplot/axis.h
<reponame>JackDinsmore/SimplePlots #pragma once #include "standard.h" #include "colors.h" #include <string> #include <windows.h> namespace SimplePlot { class Axis { public: Axis(std::string label = "", bool logarithmic = false, SimplePlot::Style::Color backColor = SimplePlot::Style::Color::WHITE, SimplePlot::Style::Color color = SimplePlot::Style::Color::BLACK); Axis(std::string label, float maxT, float minT, bool logarithmic = false, SimplePlot::Style::Color backColor = SimplePlot::Style::Color::WHITE, SimplePlot::Style::Color color = SimplePlot::Style::Color::BLACK); ~Axis(); bool setEnds(float minT_, float maxT_); int getClearance(); void drawGrid(HDC hdc, POINT origin, POINT axisEnd, POINT gridEnd); void drawAxis(HDC hdc, POINT origin, POINT axisEnd, POINT gridEnd); bool grid = true; private: void setMajorMinor(); void makePen(); bool logarithmic = false; bool fixEnds; float maxT; float minT; float major; float minor; std::wstring label; SimplePlot::Style::Color color; SimplePlot::Style::Color backColor; HPEN thickPen, thinPen, backPen; HFONT labelFont; HFONT tickFont; }; namespace Axes { int getNumAxes(AXIS_TYPE t); int getNumAxisCorners(AXIS_TYPE t); } }
JackDinsmore/SimplePlots
simpleplot/colors.h
#pragma once #include <windows.h> #define SP_BLACK 0x0 #define SP_PURPLE 0x1 #define SP_GREEN 0x2 #define SP_BLUE 0x3 #define SP_WHITE 0x10// Not actually a color scheme #define SP_SOLID 0x00 #define SP_DASH 0x10 #define SP_DOT 0x20 #define SP_DASHDOT 0x30 #define SP_DASHDOTDOT 0x40 #define SP_MEDIUM 0x000 #define SP_THIN 0x100 #define SP_THICK 0x200 namespace SimplePlot { namespace Style { typedef unsigned long SP_COLORREF; enum class Color { WHITE, BLACK, RED, YELLOW, LIGHT_GREEN, GREEN, LIGHT_BLUE, BLUE, TEAL, LIGHT_PURPLE, PURPLE, GRAY, }; SP_COLORREF getColor(SimplePlot::Style::Color color); class Style { public: Style() {} Style(int); ~Style(); public: HBRUSH foreBrush = NULL; HBRUSH backBrush = NULL; HPEN forePen = NULL; HPEN backPen = NULL; int foreStyle; }; } }
JackDinsmore/SimplePlots
simpleplot/canvas.h
#pragma once #include <windows.h> #include <string> #include <vector> #include "standard.h" #include "axis.h" namespace SimplePlot { namespace Canvas { class Canvas { public: Canvas(std::vector<PLOT_ID> plots_, std::wstring name, int style); ~Canvas(); void setPos(int x, int y); void setSize(int cx, int cy); void rename(std::string s); POINT getSize(); POINT getPos(); void setFramerate(int framerate_); void addPlot(PLOT_ID plotID); void removePlot(PLOT_ID plotID); void launch(); bool isEmpty(); void setGridLines(bool state); std::string title; HWND hwnd; CANVAS_ID id = SP_NULL_CANVAS; bool legend = false; bool enforceSquare = false; private: void initWindow(); void paint(); void draw(HDC hdc); void createBitmap(); void setAxisType(); void kill(); inline static CANVAS_ID maxID; std::vector<PLOT_ID> plots; int framerate = SP_DYNAMIC; AXIS_TYPE axisType; int numAxes = 0; int numCorners = 0; std::string* axisTitles; Axis* axes; float* axisLimits; POINT* drawSpace; std::wstring name; std::vector<std::wstring> plotNames; bool killed = false; SimplePlot::Style::Style style; }; } CANVAS_ID makeCanvas(std::vector<PLOT_ID> plots, std::wstring name = L"", int style = 0); void deleteCanvas(CANVAS_ID id); void addPlotToCanvas(CANVAS_ID canvasID, PLOT_ID plotID); void removePlotFromCanvas(CANVAS_ID canvasID, PLOT_ID plotID); void setCanvasGridLines(CANVAS_ID canvasID, bool state); void setCanvasFramerate(CANVAS_ID id, int framerate); void setCanvasLegend(CANVAS_ID id, bool legend); void setCanvasEnforceSquare(CANVAS_ID id, bool sq); }
maksimandrianov/cdstructures
include/cdcontainers/casts.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_CASTS_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_CASTS_H #include <float.h> #include <limits.h> #include <stddef.h> #include <stdint.h> #define CDC_TO_CHAR(p) ((char)(intptr_t)(p)) #define CDC_FROM_CHAR(s) ((void *)(intptr_t)(char)(s)) #define CDC_TO_SCHAR(p) ((signed char)(intptr_t)(p)) #define CDC_FROM_SCHAR(s) ((void *)(intptr_t)(signed char)(s)) #define CDC_TO_UCHAR(p) ((unsigned char)(uintptr_t)(p)) #define CDC_FROM_UCHAR(s) ((void *)(uintptr_t)(unsigned char)(s)) #define CDC_TO_SHORT(p) ((short)(intptr_t)(p)) #define CDC_FROM_SHORT(s) ((void *)(intptr_t)(short)(s)) #define CDC_TO_USHORT(p) ((unsigned short)(uintptr_t)(p)) #define CDC_FROM_USHORT(s) ((void *)(uintptr_t)(unsigned short)(s)) #define CDC_TO_INT(p) ((int)(intptr_t)(p)) #define CDC_FROM_INT(s) ((void *)(intptr_t)(int)(s)) #define CDC_TO_UINT(p) ((unsigned int)(uintptr_t)(p)) #define CDC_FROM_UINT(s) ((void *)(uintptr_t)(unsigned int)(s)) #define CDC_TO_SIZE(p) ((size_t)(uintptr_t)(p)) #define CDC_FROM_SIZE(s) ((void *)(uintptr_t)(size_t)(s)) #if UINTPTR_MAX >= ULONG_MAX #define CDC_TO_LONG(p) ((long)(intptr_t)(p)) #define CDC_FROM_LONG(s) ((void *)(intptr_t)(long)(s)) #define CDC_LONG_CAST #define CDC_TO_ULONG(p) ((unsigned long)(uintptr_t)(p)) #define CDC_FROM_ULONG(s) ((void *)(uintptr_t)(unsigned long)(s)) #define CDC_ULONG_CAST #endif #if (defined(__GNUC__)) && defined(__SIZEOF_POINTER__) #if defined(__SIZEOF_FLOAT__) && (__SIZEOF_POINTER__ >= __SIZEOF_FLOAT__) union cdc_union_float_ptr { void *ptr; float flt; }; static inline void *cdc_float_to_ptr(float flt) { union cdc_union_float_ptr u; u.flt = flt; return u.ptr; } static inline float cdc_ptr_to_float(void *ptr) { union cdc_union_float_ptr u; u.ptr = ptr; return u.flt; } #define CDC_TO_FLOAT(p) cdc_ptr_to_float(p) #define CDC_FROM_FLOAT(s) cdc_float_to_ptr(s) #define CDC_FLOAT_CAST #endif #if defined(__SIZEOF_DOUBLE__) && (__SIZEOF_POINTER__ >= __SIZEOF_DOUBLE__) union cdc_union_double_ptr { void *ptr; double dbl; }; static inline void *cdc_double_to_ptr(double dbl) { union cdc_union_double_ptr u; u.dbl = dbl; return u.ptr; } static inline double cdc_ptr_to_double(void *ptr) { union cdc_union_double_ptr u; u.ptr = ptr; return u.dbl; } #define CDC_TO_DOUBLE(p) cdc_ptr_to_double(p) #define CDC_FROM_DOUBLE(s) cdc_double_to_ptr(s) #define CDC_DOUBLE_CAST #endif #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_CASTS_H
maksimandrianov/cdstructures
include/cdcontainers/hash.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief This file contains different utilities for hashing. * The ideas of algorithms were borrowed from the boost library. * http://www.boost.org/doc/libs/1_64_0/boost/functional/hash/hash.hpp * http://www.boost.org/doc/libs/1_64_0/boost/functional/hash/detail/hash_float.hpp */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_H #include <cdcontainers/casts.h> #include <float.h> #include <limits.h> #include <stddef.h> #include <string.h> typedef size_t (*cdc_hash_fn_t)(void const *); #define CDC_DIGITS_CHAR (CHAR_BIT - (CHAR_MIN < 0)) #define CDC_DIGITS_SCHAR (CHAR_BIT - 1) #define CDC_DIGITS_UCHAR (CHAR_BIT) #define CDC_DIGITS_SHORT (CHAR_BIT * sizeof(short) - 1) #define CDC_DIGITS_USHORT (CHAR_BIT * sizeof(short)) #define CDC_DIGITS_INT (CHAR_BIT * sizeof(int) - 1) #define CDC_DIGITS_UINT (CHAR_BIT * sizeof(int)) #define CDC_DIGITS_LONG (CHAR_BIT * sizeof(long) - 1) #define CDC_DIGITS_ULONG (CHAR_BIT * sizeof(long)) #define CDC_DIGITS_SIZE (CHAR_BIT * sizeof(size_t)) #define MAKE_SIGNED_HASH(T, DIGITS, NAME) \ static inline size_t cdc_hash_##NAME(T val) \ { \ const unsigned int size_t_bits = CDC_DIGITS_SIZE; \ const int length = (DIGITS - 1) / (int)(size_t_bits); \ unsigned int i; \ size_t seed = 0; \ T positive = val < 0 ? -1 - val : val; \ for (i = length * size_t_bits; i > 0; i -= size_t_bits) \ seed ^= (size_t)(positive >> i) + (seed << 6) + (seed >> 2); \ seed ^= (size_t)val + (seed << 6) + (seed >> 2); \ return seed; \ } #define MAKE_UNSIGNED_HASH(T, DIGITS, NAME) \ static inline size_t cdc_hash_##NAME(T val) \ { \ const unsigned int size_t_bits = CDC_DIGITS_SIZE; \ const int length = (DIGITS - 1) / (int)(size_t_bits); \ unsigned int i; \ size_t seed = 0; \ for (i = length * size_t_bits; i > 0; i -= size_t_bits) \ seed ^= (size_t)(seed >> i) + (seed << 6) + (seed >> 2); \ seed ^= (size_t)val + (seed << 6) + (seed >> 2); \ return seed; \ } static inline size_t cdc_hash_float_combine(size_t seed, size_t value) { seed ^= value + (seed << 6) + (seed >> 2); return seed; } static inline size_t cdc_hash_binary(char *ptr, size_t length) { size_t seed = 0; if (length >= sizeof(size_t)) { memcpy(&seed, ptr, sizeof(size_t)); length -= sizeof(size_t); ptr += sizeof(size_t); while (length >= sizeof(size_t)) { size_t buffer = 0; memcpy(&buffer, ptr, sizeof(size_t)); seed = cdc_hash_float_combine(seed, buffer); length -= sizeof(size_t); ptr += sizeof(size_t); } } if (length > 0) { size_t buffer = 0; memcpy(&buffer, ptr, length); seed = cdc_hash_float_combine(seed, buffer); } return seed; } #define MAKE_FLOAT_HASH(T, NAME) \ static inline size_t cdc_hash_##NAME(T val) \ { \ return cdc_hash_binary((char *)&val, sizeof(T)); \ } MAKE_SIGNED_HASH(signed char, CDC_DIGITS_SCHAR, schar) MAKE_SIGNED_HASH(short, CDC_DIGITS_SHORT, short) MAKE_SIGNED_HASH(int, CDC_DIGITS_INT, int) MAKE_SIGNED_HASH(long, CDC_DIGITS_LONG, long) MAKE_FLOAT_HASH(float, float) MAKE_FLOAT_HASH(double, double) MAKE_FLOAT_HASH(long double, ldouble) MAKE_UNSIGNED_HASH(unsigned char, CDC_DIGITS_UCHAR, uchar) MAKE_UNSIGNED_HASH(unsigned short, CDC_DIGITS_USHORT, ushort) MAKE_UNSIGNED_HASH(unsigned int, CDC_DIGITS_UINT, uint) MAKE_UNSIGNED_HASH(unsigned long, CDC_DIGITS_ULONG, ulong) #if CHAR_MIN < 0 MAKE_SIGNED_HASH(char, CDC_DIGITS_CHAR, char) #else MAKE_UNSIGNED_HASH(char, CDC_DIGITS_CHAR, char) #endif #define MAKE_POINTER_DATA_HASH(T, NAME, CAST_FUNC) \ static inline size_t cdc_pdhash_##NAME(void *val) \ { \ T t = CAST_FUNC(val); \ return cdc_hash_##NAME(t); \ } MAKE_POINTER_DATA_HASH(char, char, CDC_TO_CHAR) MAKE_POINTER_DATA_HASH(signed char, schar, CDC_TO_SCHAR) MAKE_POINTER_DATA_HASH(unsigned char, uchar, CDC_TO_UCHAR) MAKE_POINTER_DATA_HASH(short, short, CDC_TO_SHORT) MAKE_POINTER_DATA_HASH(unsigned short, ushort, CDC_TO_USHORT) MAKE_POINTER_DATA_HASH(int, int, CDC_TO_INT) MAKE_POINTER_DATA_HASH(unsigned int, uint, CDC_TO_UINT) #ifdef CDC_LONG_CAST MAKE_POINTER_DATA_HASH(long, long, CDC_TO_LONG) MAKE_POINTER_DATA_HASH(unsigned long, ulong, CDC_TO_ULONG) #endif #ifdef CDC_FLOAT_CAST MAKE_POINTER_DATA_HASH(float, float, CDC_TO_FLOAT) #endif #ifdef CDC_DOUBLE_CAST MAKE_POINTER_DATA_HASH(double, double, CDC_TO_DOUBLE) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_H
maksimandrianov/cdstructures
tests/test-queue.c
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/adapters/queue.h" #include "cdcontainers/casts.h" #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> void test_queued_ctor() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctor(tables[t], &q, NULL), CDC_STATUS_OK); CU_ASSERT(queue_empty(q)); queue_dtor(q); } } void test_queued_ctorl() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 2, b = 3; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctorl(tables[t], &q, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(queue_size(q), 2); void *elem = queue_front(q); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); queue_pop(q); CU_ASSERT_EQUAL(queue_size(q), 1); elem = queue_front(q); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); queue_pop(q); CU_ASSERT_EQUAL(queue_size(q), 0); queue_dtor(q); } } void test_queued_push() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 0, b = 1, c = 2; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctor(tables[t], &q, NULL), CDC_STATUS_OK); queue_push(q, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(queue_size(q), 1); void *elem = queue_back(q); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); queue_push(q, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(queue_size(q), 2); elem = queue_back(q); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); queue_push(q, CDC_FROM_INT(c)); CU_ASSERT_EQUAL(queue_size(q), 3); elem = queue_back(q); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); queue_dtor(q); } } void test_queued_pop() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 0, b = 1, c = 2, d = 3; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctorl(tables[t], &q, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = queue_front(q); queue_pop(q); CU_ASSERT_EQUAL(queue_size(q), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); elem = queue_front(q); queue_pop(q); CU_ASSERT_EQUAL(queue_size(q), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = queue_front(q); queue_pop(q); CU_ASSERT_EQUAL(queue_size(q), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = queue_front(q); queue_pop(q); CU_ASSERT(queue_empty(q)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); queue_dtor(q); } } void test_queued_front() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 1, b = 2; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctorl(tables[t], &q, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(queue_front(q)), a); queue_dtor(q); } } void test_queued_back() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 1, b = 2; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *q = NULL; CU_ASSERT_EQUAL(queue_ctorl(tables[t], &q, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(queue_back(q)), b); queue_dtor(q); } } void test_queued_swap() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 2, b = 3, c = 4; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { queue_t *v = NULL; queue_t *w = NULL; CU_ASSERT_EQUAL(queue_ctorl(tables[t], &v, NULL, CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(queue_ctorl(tables[t], &w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); queue_swap(v, w); CU_ASSERT_EQUAL(queue_size(v), 2); CU_ASSERT_EQUAL(CDC_TO_INT(queue_back(v)), c); CU_ASSERT_EQUAL(queue_size(w), 1); CU_ASSERT_EQUAL(CDC_TO_INT(queue_back(w)), b); queue_dtor(v); queue_dtor(w); } }
maksimandrianov/cdstructures
include/cdcontainers/adapters/map.h
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file map.h * @brief The cdc_map is a struct and functions that provide a map. * * Example usage map: * @include map.c * * @author <NAME> <<EMAIL>> */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_MAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_MAP_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <cdcontainers/tables/imap.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> /** * @defgroup cdc_map * @brief The cdc_map is a struct and functions that provide a map. * @{ */ /** * @brief The cdc_map is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_map { void *container; const struct cdc_map_table *table; }; /** * @brief The cdc_map_iter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_map_iter { void *iter; const struct cdc_map_iter_table *table; }; // Base /** * @defgroup cdc_map_base Base * @{ */ /** * @brief Constructs an empty map. * @param[in] table - table of a map implementation. It can be cdc_map_avl, * cdc_map_splay, cdc_map_map, cdc_map_htable. * @param[out] m - cdc_map * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example of map constracting with hash table implementation: * @code{.c} * struct cdc_map *map = NULL; * ... * if (cdc_map_ctor(cdc_map_ctor, map, info) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_map_ctor(const struct cdc_map_table *table, struct cdc_map **m, struct cdc_data_info *info); /** * @brief Constructs a map, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[in] table - table of a map implementation. It can be cdc_map_avl, * cdc_map_splay, cdc_map_map, cdc_map_htable. * @param[out] m - cdc_map * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_map *map = NULL; * cdc_pair value1 = {CDC_FROM_INT(1), CDC_FROM_INT(2)}; * cdc_pair value2 = {CDC_FROM_INT(3), CDC_FROM_INT(4)}; * ... * if (cdc_map_ctorl(cdc_map_avl, &tree, info, &value1, &value2, CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_map_ctorl(const struct cdc_map_table *table, struct cdc_map **m, struct cdc_data_info *info, ...); /** * @brief Constructs a map, initialized by args. The last item must be * CDC_END. * @param[in] table - table of a map implementation. It can be cdc_map_avl, * cdc_map_splay, cdc_map_map, cdc_map_htable. * @param[out] m - cdc_map * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_map_ctorv(const struct cdc_map_table *table, struct cdc_map **m, struct cdc_data_info *info, va_list args); /** * @brief Destroys the map. * @param[in] t - cdc_map */ void cdc_map_dtor(struct cdc_map *m); /** @} */ // Lookup /** * @defgroup cdc_map_lookup Lookup * @{ */ /** * @brief Returns a value that is mapped to a key. If the key does * not exist, then NULL will return. * @param[in] m - cdc_map * @param[in] key - key of the element to find * @param[out] value - pinter to the value that is mapped to a key. * @return CDC_STATUS_OK if the key is found, CDC_STATUS_NOT_FOUND otherwise. */ static inline enum cdc_stat cdc_map_get(struct cdc_map *m, void *key, void **value) { assert(m != NULL); return m->table->get(m->container, key, value); } /** * @brief Returns the number of elements with key that compares equal to the * specified argument key, which is either 1 or 0 since this container does not * allow duplicates. * @param[in] m - cdc_map * @param[in] key - key value of the elements to count * @return number of elements with key key, that is either 1 or 0. */ static inline size_t cdc_map_count(struct cdc_map *m, void *key) { assert(m != NULL); return m->table->count(m->container, key); } /** * @brief Finds an element with key equivalent to key. * @param[in] m - cdc_map * @param[in] key - key value of the element to search for * @param[out] it - pointer will be recorded iterator to an element with key * equivalent to key. If no such element is found, past-the-end iterator is * returned. */ static inline void cdc_map_find(struct cdc_map *m, void *key, struct cdc_map_iter *it) { assert(m != NULL); m->table->find(m->container, key, it->iter); } /** @} */ // Capacity /** * @defgroup cdc_map_capacity Capacity * @{ */ /** * @brief Returns the number of items in the map. * @param[in] m - cdc_map * @return the number of items in the map. */ static inline size_t cdc_map_size(struct cdc_map *m) { assert(m != NULL); return m->table->size(m->container); } /** * @brief Checks if the map has no elements. * @param[in] m - cdc_map * @return true if the map is empty, false otherwise. */ static inline bool cdc_map_empty(struct cdc_map *m) { assert(m != NULL); return m->table->empty(m->container); } /** @} */ // Modifiers /** * @defgroup cdc_map_modifiers Modifiers * @{ */ /** * @brief Removes all the elements from the map. * @param[in] m - cdc_map */ static inline void cdc_map_clear(struct cdc_map *m) { assert(m != NULL); m->table->clear(m->container); } /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] m - cdc_map * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator to the inserted element (or to the element that * prevented the insertion). The pointer can be equal to NULL. * @param[out] inserted - bool denoting whether the insertion * took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ static inline enum cdc_stat cdc_map_insert(struct cdc_map *m, void *key, void *value, struct cdc_map_iter *it, bool *inserted) { assert(m != NULL); void *iter = it ? it->iter : NULL; return m->table->insert(m->container, key, value, iter, inserted); } /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] m - cdc_map * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator is pointing at the element that was inserted or updated. * The pointer can be equal to NULL * @param[out] inserted - bool is true if the insertion took place and false if the * assignment took place. The pointer can be equal to NULL * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ static inline enum cdc_stat cdc_map_insert_or_assign(struct cdc_map *m, void *key, void *value, struct cdc_map_iter *it, bool *inserted) { assert(m != NULL); void *iter = it ? it->iter : NULL; return m->table->insert_or_assign(m->container, key, value, iter, inserted); } /** * @brief Removes the element (if one exists) with the key equivalent to key. * @param[in] m - cdc_map * @param[in] key - key value of the elements to remove * @return number of elements removed. */ static inline size_t cdc_map_erase(struct cdc_map *m, void *key) { assert(m != NULL); return m->table->erase(m->container, key); } /** * @brief Swaps maps a and b. This operation is very fast and never fails. * @param[in, out] a - cdc_map * @param[in, out] b - cdc_map */ static inline void cdc_map_swap(struct cdc_map *a, struct cdc_map *b) { assert(a != NULL); assert(b != NULL); assert(a->table == b->table); CDC_SWAP(void *, a->container, b->container); } /** @} */ // Iterators /** * @defgroup cdc_map_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param[in] m - cdc_map * @param[out] out - cdc_map_iter */ static inline void cdc_map_begin(struct cdc_map *m, struct cdc_map_iter *it) { assert(m != NULL); assert(it != NULL); m->table->begin(m->container, it->iter); } /** * @brief Initializes the iterator to the end. * @param[in] m - cdc_map * @param[out] it - iterator */ static inline void cdc_map_end(struct cdc_map *m, struct cdc_map_iter *it) { assert(m != NULL); assert(it != NULL); m->table->end(m->container, it->iter); } /** @} */ // Iterators /** * @defgroup cdc_map_iter * @brief The cdc_map_iter is a struct and functions that provide a map iterator. * @{ */ /** * @brief Constructs a map iterator. Should be called for each new iterator. * @param[in] t - cdc_map * @param[out] it - iterator * * Example: * @code{.c} * struct cdc_map *map = NULL; * ... * struct cdc_map_iter it = CDC_INIT_STRUCT; * if (cdc_map_iter_ctor(map, &it) != CDC_STATUS_OK) { * // handle error * } * * cdc_map_begin(map, &it); * while (cdc_map_iter_has_next(&it)) { * void *value = cdc_map_iter_value(&it); * ... * cdc_map_iter_next(&it); * } * * @endcode */ enum cdc_stat cdc_map_iter_ctor(struct cdc_map *m, struct cdc_map_iter *it); /** * @brief Destroys the iterator. It should be called after the iterator is no * longer needed. Releases resources. * @param[in] it - iterator */ static inline void cdc_map_iter_dtor(struct cdc_map_iter *it) { assert(it != NULL); it->table->dtor(it->iter); } /** * @brief Returns a type of iterator. * @param[in] it - iterator * @return a type of iterator. */ static inline enum cdc_iterator_type cdc_map_iter_type(struct cdc_map_iter *it) { assert(it != NULL); return it->table->type(); } /** * @brief Advances the iterator to the next element in the map. * @param[in] it - iterator */ static inline void cdc_map_iter_next(struct cdc_map_iter *it) { assert(it != NULL); it->table->next(it->iter); } /** * @brief Advances the iterator to the previous element in the map. * @param[in] it - iterator */ static inline void cdc_map_iter_prev(struct cdc_map_iter *it) { assert(it != NULL); it->table->prev(it->iter); } /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_map_iter_has_next(struct cdc_map_iter *it) { assert(it != NULL); return it->table->has_next(it->iter); } /** * @brief Returns true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. */ static inline bool cdc_map_iter_has_prev(struct cdc_map_iter *it) { assert(it != NULL); return it->table->has_prev(it->iter); } /** * @brief Returns an item's key. * @param[in] it - iterator * @return the item's key. */ static inline void *cdc_map_iter_key(struct cdc_map_iter *it) { assert(it != NULL); return it->table->key(it->iter); } /** * @brief Returns an item's value. * @param[in] it - iterator * @return the item's value. */ static inline void *cdc_map_iter_value(struct cdc_map_iter *it) { assert(it != NULL); return it->table->value(it->iter); } /** * @brief Returns a pair, where first - key, second - value. * @param[in] it - iterator * @return pair, where first - key, second - value. */ static inline struct cdc_pair cdc_map_iter_key_value(struct cdc_map_iter *it) { assert(it != NULL); return it->table->key_value(it->iter); } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_map_iter_is_eq(struct cdc_map_iter *it1, struct cdc_map_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); assert(it1->table == it2->table); return it1->table->eq(it1->iter, it2->iter); } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_map map_t; typedef struct cdc_map_iter map_iter_t; // Base #define map_ctor(...) cdc_map_ctor(__VA_ARGS__) #define map_ctorv(...) cdc_map_ctorv(__VA_ARGS__) #define map_ctorl(...) cdc_map_ctorl(__VA_ARGS__) #define map_dtor(...) cdc_map_dtor(__VA_ARGS__) // Lookup #define map_get(...) cdc_map_get(__VA_ARGS__) #define map_count(...) cdc_map_count(__VA_ARGS__) #define map_find(...) cdc_map_find(__VA_ARGS__) // Capacity #define map_size(...) cdc_map_size(__VA_ARGS__) #define map_empty(...) cdc_map_empty(__VA_ARGS__) // Modifiers #define map_clear(...) cdc_map_clear(__VA_ARGS__) #define map_insert(...) cdc_map_insert(__VA_ARGS__) #define map_insert_or_assign(...) cdc_map_insert_or_assign(__VA_ARGS__) #define map_erase(...) cdc_map_erase(__VA_ARGS__) #define map_swap(...) cdc_map_swap(__VA_ARGS__) // Iterators #define map_begin(...) cdc_map_begin(__VA_ARGS__) #define map_end(...) cdc_map_end(__VA_ARGS__) // Iterators #define map_iter_ctor(...) cdc_map_iter_ctor(__VA_ARGS__) #define map_iter_dtor(...) cdc_map_iter_dtor(__VA_ARGS__) #define map_iter_next(...) cdc_map_iter_next(__VA_ARGS__) #define map_iter_prev(...) cdc_map_iter_prev(__VA_ARGS__) #define map_iter_has_next(...) cdc_map_iter_has_next(__VA_ARGS__) #define map_iter_has_prev(...) cdc_map_iter_has_prev(__VA_ARGS__) #define map_iter_key(...) cdc_map_iter_key(__VA_ARGS__) #define map_iter_value(...) cdc_map_iter_value(__VA_ARGS__) #define map_iter_key_value(...) cdc_map_iter_key_value(__VA_ARGS__) #define map_iter_is_eq(...) cdc_map_iter_is_eq(__VA_ARGS__) #define map_iter_type(...) cdc_map_iter_type(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_MAP_H
maksimandrianov/cdstructures
src/adapters/map.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/adapters/map.h" #include "cdcontainers/data-info.h" stat_t map_ctor(const map_table_t *table, map_t **m, data_info_t *info) { assert(table != NULL); assert(m != NULL); assert(CDC_HAS_CMP(info)); map_t *tmp = (map_t *)malloc(sizeof(map_t)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } tmp->table = table; stat_t stat = tmp->table->ctor(&tmp->container, info); if (stat != CDC_STATUS_OK) { free(tmp); return stat; } *m = tmp; return CDC_STATUS_OK; } stat_t map_ctorl(const map_table_t *table, map_t **m, data_info_t *info, ...) { assert(table != NULL); assert(m != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t stat = map_ctorv(table, m, info, args); va_end(args); return stat; } stat_t map_ctorv(const map_table_t *table, map_t **m, data_info_t *info, va_list args) { assert(table != NULL); assert(m != NULL); assert(CDC_HAS_CMP(info)); map_t *tmp = (map_t *)malloc(sizeof(map_t)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } tmp->table = table; stat_t stat = tmp->table->ctorv(&tmp->container, info, args); if (stat != CDC_STATUS_OK) { free(tmp); return stat; } *m = tmp; return stat; } void map_dtor(map_t *m) { assert(m != NULL); m->table->dtor(m->container); free(m); } stat_t map_iter_ctor(map_t *m, map_iter_t *it) { assert(m != NULL); assert(it != NULL); it->table = m->table->iter_table; it->iter = it->table->ctor(); if (!it->iter) { return CDC_STATUS_BAD_ALLOC; } return CDC_STATUS_OK; }
maksimandrianov/cdstructures
include/cdcontainers/binomial-heap.h
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_binomial_heap is a struct and functions that provide a * binomial heap */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_BINOMIAL_HEAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_BINOMIAL_HEAP_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_binomial_heap_node struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_binomial_heap_node { struct cdc_binomial_heap_node *parent; struct cdc_binomial_heap_node *child; struct cdc_binomial_heap_node *sibling; size_t degree; void *key; }; /** * @brief The cdc_binomial_heap struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_binomial_heap { struct cdc_binomial_heap_node *root; struct cdc_binomial_heap_node *top; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_binomial_heap_iter struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_binomial_heap_iter { struct cdc_binomial_heap *container; struct cdc_binomial_heap_node *current; }; /** * @brief Constructs an empty binomial heap. * @param h - cdc_binomial_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_binomial_heap_ctor(struct cdc_binomial_heap **h, struct cdc_data_info *info); /** * @brief Constructs a binomial heap, initialized by an arbitrary number of * pointers. The last item must be NULL. * @param h - cdc_binomial_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_binomial_heap_ctorl(struct cdc_binomial_heap **h, struct cdc_data_info *info, ...); /** * @brief Constructs a binomial heap, initialized by args. The last item must be * NULL. * @param h - cdc_binomial_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_binomial_heap_ctorv(struct cdc_binomial_heap **h, struct cdc_data_info *info, va_list args); /** * @brief Destroys the binomial heap. * @param h - cdc_binomial_heap */ void cdc_binomial_heap_dtor(struct cdc_binomial_heap *h); // Element access /** * @brief Returns a pointer to the binomial heap's top item. This function * assumes that the binomial heap isn't empty. * @param h - cdc_binomial_heap * @return top item */ static inline void *cdc_binomial_heap_top(struct cdc_binomial_heap *h) { assert(h != NULL); return h->top->key; } // Capacity /** * @brief Returns the number of items in the binomial heap. * @param h - cdc_binomial_heap * @return size */ static inline size_t cdc_binomial_heap_size(struct cdc_binomial_heap *h) { assert(h != NULL); return h->size; } /** * @brief Returns true if the binomial heap has size 0; otherwise returns false. * @param h - cdc_binomial_heap * @return true if the binomial heap has size 0; otherwise returns false */ static inline bool cdc_binomial_heap_empty(struct cdc_binomial_heap *h) { assert(h != NULL); return h->size == 0; } // Modifiers /** * @brief Extracts the top item from the binomial heap. This function assumes * that the binomial heap isn't empty. * @param h - cdc_binomial_heap * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_binomial_heap_extract_top(struct cdc_binomial_heap *h); /** * @brief Inserts element key to the binomial heap. Write an iterator pointing * to a new element in the ret * @param h - cdc_binomial_heap * @param key * @param ret - pointer to iterator where an iterator will be written indicating * the inserted element * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_binomial_heap_riinsert(struct cdc_binomial_heap *h, void *key, struct cdc_binomial_heap_iter *ret); /** * @brief Inserts element key to the binomial heap. * @param h - cdc_binomial_heap * @param key * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_binomial_heap_insert(struct cdc_binomial_heap *h, void *key) { assert(h != NULL); return cdc_binomial_heap_riinsert(h, key, NULL); } /** * @brief Changes the item key on the pos position in the binomial heap. * @param h - cdc_binomial_heap * @param pos - iterator that indicates the item with key that you want to * change * @param key */ void cdc_binomial_heap_change_key(struct cdc_binomial_heap *h, struct cdc_binomial_heap_iter *pos, void *key); /** * @brief Removes all the elements from the binomial heap. * @param h - cdc_binomial_heap */ void cdc_binomial_heap_clear(struct cdc_binomial_heap *h); /** * @brief Swaps binomial heaps a and b. This operation is very fast and never * fails. * @param a - cdc_binomial_heap * @param b - cdc_binomial_heap */ void cdc_binomial_heap_swap(struct cdc_binomial_heap *a, struct cdc_binomial_heap *b); // Operations /** * @brief Merges two heaps. In the heap h will be the result of the merger, * and the heap other will remain empty. * @param h - cdc_binomial_heap * @param other - cdc_binomial_heap */ void cdc_binomial_heap_merge(struct cdc_binomial_heap *h, struct cdc_binomial_heap *other); /** * @brief Checks the heap property. * @param h - cdc_binomial_heap * @return result of the check */ bool cdc_binomial_heap_is_heap(struct cdc_binomial_heap *h); // Iterators /** * @brief Returns a pointer to the key of current item. */ static inline void *cdc_binomial_heap_iter_data(struct cdc_binomial_heap_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns false if the iterator it1 equal to the iterator it2, * otherwise returns false */ static inline bool cdc_binomial_heap_iter_is_eq(struct cdc_binomial_heap_iter *it1, struct cdc_binomial_heap_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->current == it2->current; } // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_binomial_heap_node binomial_heap_node_t; typedef struct cdc_binomial_heap binomial_heap_t; typedef struct cdc_binomial_heap_iter binomial_heap_iter_t; #define binomial_heap_ctor(...) cdc_binomial_heap_ctor(__VA_ARGS__) #define binomial_heap_ctorl(...) cdc_binomial_heap_ctorl(__VA_ARGS__) #define binomial_heap_ctorv(...) cdc_binomial_heap_ctorv(__VA_ARGS__) #define binomial_heap_dtor(...) cdc_binomial_heap_dtor(__VA_ARGS__) // Element access #define binomial_heap_top(...) cdc_binomial_heap_top(__VA_ARGS__) // Capacity #define binomial_heap_empty(...) cdc_binomial_heap_empty(__VA_ARGS__) #define binomial_heap_size(...) cdc_binomial_heap_size(__VA_ARGS__) // Modifiers #define binomial_heap_extract_top(...) cdc_binomial_heap_extract_top(__VA_ARGS__) #define binomial_heap_riinsert(...) cdc_binomial_heap_riinsert(__VA_ARGS__) #define binomial_heap_insert(...) cdc_binomial_heap_insert(__VA_ARGS__) #define binomial_heap_change_key(...) cdc_binomial_heap_change_key(__VA_ARGS__) #define binomial_heap_clear(...) cdc_binomial_heap_clear(__VA_ARGS__) #define binomial_heap_swap(...) cdc_binomial_heap_swap(__VA_ARGS__) // Operations #define binomial_heap_merge(...) cdc_binomial_heap_merge(__VA_ARGS__) #define binomial_heap_is_heap(...) cdc_binomial_heap_is_heap(__VA_ARGS__) // Iterators #define binomial_heap_iter_data(...) cdc_binomial_heap_iter_data(__VA_ARGS__) #define binomial_heap_iter_is_eq(...) cdc_binomial_heap_iter_is_eq(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_BINOMIAL_HEAP_H
maksimandrianov/cdstructures
src/data-info.c
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/data-info.h" #include <assert.h> #include <stdlib.h> #include <string.h> data_info_t *di_shared_ctorc(data_info_t *other) { assert(other != NULL); if (other->__cnt++ != 0) { return other; } data_info_t *result = (data_info_t *)malloc(sizeof(data_info_t)); if (result) { memcpy(result, other, sizeof(data_info_t)); } return result; } void di_shared_dtor(data_info_t *info) { if (info && --info->__cnt == 0) { free(info); } }
maksimandrianov/cdstructures
tests/test-map.c
<filename>tests/test-map.c // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/adapters/map.h" #include "cdcontainers/casts.h" #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> static pair_t a = {CDC_FROM_INT(0), CDC_FROM_INT(0)}; static pair_t b = {CDC_FROM_INT(1), CDC_FROM_INT(1)}; static pair_t c = {CDC_FROM_INT(2), CDC_FROM_INT(2)}; static pair_t d = {CDC_FROM_INT(3), CDC_FROM_INT(3)}; static pair_t e = {CDC_FROM_INT(4), CDC_FROM_INT(4)}; static pair_t f = {CDC_FROM_INT(5), CDC_FROM_INT(5)}; static pair_t g = {CDC_FROM_INT(6), CDC_FROM_INT(6)}; static pair_t h = {CDC_FROM_INT(7), CDC_FROM_INT(7)}; static int lt(const void *l, const void *r) { return CDC_TO_INT(l) < CDC_TO_INT(r); } static int eq(const void *l, const void *r) { return CDC_TO_INT(l) == CDC_TO_INT(r); } static size_t hash(const void *val) { return cdc_hash_int(CDC_TO_INT(val)); } static bool map_key_int_eq(map_t *t, size_t count, ...) { va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { pair_t *val = va_arg(args, pair_t *); void *tmp = NULL; if (cdc_map_get(t, val->first, &tmp) != CDC_STATUS_OK || tmp != val->second) { va_end(args); return false; } } va_end(args); return true; } void test_map_ctor() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctor(tables[t], &m, &info), CDC_STATUS_OK); CU_ASSERT(map_empty(m)); map_dtor(m); } } void test_map_ctorl() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &g, &h, &d, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 4); CU_ASSERT(map_key_int_eq(m, 4, &a, &g, &h, &d)); map_dtor(m); } } void test_map_get() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 8); CU_ASSERT(map_key_int_eq(m, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(map_get(m, CDC_FROM_INT(10), &value), CDC_STATUS_NOT_FOUND); map_dtor(m); } } void test_map_count() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 2); CU_ASSERT_EQUAL(map_count(m, a.first), 1); CU_ASSERT_EQUAL(map_count(m, b.first), 1); CU_ASSERT_EQUAL(map_count(m, CDC_FROM_INT(10)), 0); map_dtor(m); } } void test_map_find() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; map_iter_t it = CDC_INIT_STRUCT; map_iter_t it_end = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, &c, &d, &g, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_iter_ctor(m, &it), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_iter_ctor(m, &it_end), CDC_STATUS_OK); map_find(m, a.first, &it); CU_ASSERT_EQUAL(map_iter_value(&it), a.second); map_find(m, b.first, &it); CU_ASSERT_EQUAL(map_iter_value(&it), b.second); map_find(m, g.first, &it); CU_ASSERT_EQUAL(map_iter_value(&it), g.second); map_find(m, h.first, &it); map_end(m, &it_end); CU_ASSERT(map_iter_is_eq(&it, &it_end)); map_iter_dtor(&it); map_iter_dtor(&it_end); map_dtor(m); } } void test_map_clear() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 2); map_clear(m); CU_ASSERT(map_empty(m)); map_clear(m); CU_ASSERT(map_empty(m)); map_dtor(m); } } void test_map_insert() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; const int count = 100; void *val = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctor(tables[t], &m, &info), CDC_STATUS_OK); for (int i = 0; i < count; ++i) { CU_ASSERT_EQUAL(map_insert(m, CDC_FROM_INT(i), CDC_FROM_INT(i), NULL, NULL), CDC_STATUS_OK); } CU_ASSERT_EQUAL(map_size(m), count); for (int i = 0; i < count; ++i) { CU_ASSERT_EQUAL(map_get(m, CDC_FROM_INT(i), &val), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(val), i); } map_dtor(m); } } void test_map_insert_or_assign() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; map_iter_t it = CDC_INIT_STRUCT; bool inserted = false; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctor(tables[t], &m, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_iter_ctor(m, &it), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_insert_or_assign(m, a.first, a.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 1); CU_ASSERT_EQUAL(map_iter_value(&it), a.second); CU_ASSERT(inserted); CU_ASSERT_EQUAL(map_insert_or_assign(m, a.first, b.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 1); CU_ASSERT_EQUAL(map_get(m, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, b.second); CU_ASSERT_EQUAL(map_iter_value(&it), b.second); CU_ASSERT(!inserted); CU_ASSERT_EQUAL(map_insert_or_assign(m, c.first, c.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 2); CU_ASSERT_EQUAL(map_iter_value(&it), c.second); CU_ASSERT(inserted); CU_ASSERT_EQUAL(map_insert_or_assign(m, c.first, d.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 2); CU_ASSERT_EQUAL(map_get(m, c.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, d.second); CU_ASSERT_EQUAL(map_iter_value(&it), d.second); CU_ASSERT(!inserted); map_iter_dtor(&it); map_dtor(m); } } void test_map_erase() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 8); CU_ASSERT(map_key_int_eq(m, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, a.first), 1); CU_ASSERT_EQUAL(map_get(m, a.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(map_key_int_eq(m, 7, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, h.first), 1); CU_ASSERT_EQUAL(map_get(m, h.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 6); CU_ASSERT(map_key_int_eq(m, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, h.first), 0); CU_ASSERT_EQUAL(map_size(m), 6); CU_ASSERT(map_key_int_eq(m, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, b.first), 1); CU_ASSERT_EQUAL(map_get(m, b.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 5); CU_ASSERT(map_key_int_eq(m, 5, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, c.first), 1); CU_ASSERT_EQUAL(map_get(m, c.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 4); CU_ASSERT(map_key_int_eq(m, 4, &d, &g, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, d.first), 1); CU_ASSERT_EQUAL(map_get(m, d.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 3); CU_ASSERT(map_key_int_eq(m, 3, &g, &e, &f)); CU_ASSERT_EQUAL(map_erase(m, f.first), 1); CU_ASSERT_EQUAL(map_get(m, f.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 2); CU_ASSERT(map_key_int_eq(m, 2, &g, &e)); CU_ASSERT_EQUAL(map_erase(m, e.first), 1); CU_ASSERT_EQUAL(map_get(m, e.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(map_size(m), 1); CU_ASSERT(map_key_int_eq(m, 1, &g)); CU_ASSERT_EQUAL(map_erase(m, g.first), 1); CU_ASSERT_EQUAL(map_get(m, g.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(map_empty(m)); map_dtor(m); } } void test_map_swap() { } void test_map_iterators() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(map_ctorl(tables[t], &m, &info, &a, &b, &c, &d, &e, &f, &g, &h, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_size(m), 8); map_iter_t it1 = CDC_INIT_STRUCT; map_iter_t it2 = CDC_INIT_STRUCT; CU_ASSERT_EQUAL(map_iter_ctor(m, &it1), CDC_STATUS_OK); CU_ASSERT_EQUAL(map_iter_ctor(m, &it2), CDC_STATUS_OK); pair_t *arr[] = {&a, &b, &c, &d, &e, &f, &g, &h}; size_t i = 0; map_begin(m, &it1); map_end(m, &it2); for (; !map_iter_is_eq(&it1, &it2); map_iter_next(&it1)) { CU_ASSERT_EQUAL(map_iter_key(&it1), arr[i]->first) ++i; } CU_ASSERT_EQUAL(map_size(m), i); if (map_iter_type(&it1) == CDC_BIDIR_ITERATOR) { i = map_size(m) - 1; map_end(m, &it1); map_iter_prev(&it1); map_begin(m, &it2); for (; !map_iter_is_eq(&it1, &it2); map_iter_prev(&it1)) { CU_ASSERT_EQUAL(map_iter_key(&it1), arr[i]->first) --i; } CU_ASSERT_EQUAL(i, 0); } i = 0; map_begin(m, &it1); while (map_iter_has_next(&it1)) { CU_ASSERT_EQUAL(map_iter_key(&it1), arr[i]->first) ++i; map_iter_next(&it1); } if (map_size(m) != i) printf("h"); CU_ASSERT_EQUAL(map_size(m), i); if (map_iter_type(&it1) == CDC_BIDIR_ITERATOR) { i = map_size(m) - 1; map_end(m, &it1); map_iter_prev(&it1); while (map_iter_has_prev(&it1)) { CU_ASSERT_EQUAL(map_iter_key(&it1), arr[i]->first); --i; map_iter_prev(&it1); } CU_ASSERT_EQUAL(i, 0); } map_iter_dtor(&it1); map_iter_dtor(&it2); map_dtor(m); } } void test_map_iter_type() { const map_table_t *tables[] = {cdc_map_avl, cdc_map_splay, cdc_map_treap, cdc_map_htable}; const iterator_type_t answers[] = {CDC_BIDIR_ITERATOR, CDC_BIDIR_ITERATOR, CDC_BIDIR_ITERATOR, CDC_FWD_ITERATOR}; CU_ASSERT_EQUAL(CDC_ARRAY_SIZE(tables), CDC_ARRAY_SIZE(answers)); for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { map_t *m = NULL; map_iter_t it = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; info.eq = eq; info.hash = hash; map_ctor(tables[t], &m, &info); map_iter_ctor(m, &it); CU_ASSERT_EQUAL(map_iter_type(&it), answers[t]); map_iter_dtor(&it); map_dtor(m); } }
maksimandrianov/cdstructures
tests/test-avl-tree.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/avl-tree.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include "cdcontainers/tree-utils.h" #include <float.h> #include <math.h> #include <stdarg.h> #include <CUnit/Basic.h> CDC_MAKE_TREE_HEIGTH_FN(avl_tree_node_t *) static pair_t a = {CDC_FROM_INT(0), CDC_FROM_INT(0)}; static pair_t b = {CDC_FROM_INT(1), CDC_FROM_INT(1)}; static pair_t c = {CDC_FROM_INT(2), CDC_FROM_INT(2)}; static pair_t d = {CDC_FROM_INT(3), CDC_FROM_INT(3)}; static pair_t e = {CDC_FROM_INT(4), CDC_FROM_INT(4)}; static pair_t f = {CDC_FROM_INT(5), CDC_FROM_INT(5)}; static pair_t g = {CDC_FROM_INT(6), CDC_FROM_INT(6)}; static pair_t h = {CDC_FROM_INT(7), CDC_FROM_INT(7)}; static int lt(const void *l, const void *r) { return CDC_TO_INT(l) < CDC_TO_INT(r); } static inline void test_tree_links(avl_tree_node_t *node) { if (!node) return; if (node->left) { CU_ASSERT_EQUAL(node->left->parent, node); test_tree_links(node->left); } if (node->right) { CU_ASSERT_EQUAL(node->right->parent, node); test_tree_links(node->right); } } static bool avl_tree_key_int_eq(avl_tree_t *t, size_t count, ...) { test_tree_links(t->root); va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { pair_t *val = va_arg(args, pair_t *); void *tmp = NULL; if (avl_tree_get(t, val->first, &tmp) != CDC_STATUS_OK || tmp != val->second) { va_end(args); return false; } } va_end(args); CU_ASSERT_EQUAL(avl_tree_size(t), count); return true; } static inline void avl_tree_inorder_print_int(avl_tree_node_t *node) { if (node->left) { avl_tree_inorder_print_int(node->left); } printf("%d ", CDC_TO_INT(node->key)); if (node->right) { avl_tree_inorder_print_int(node->right); } } void test_avl_tree_ctor() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT(avl_tree_empty(t)); avl_tree_dtor(t); } void test_avl_tree_ctorl() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &g, &h, &d, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 4); CU_ASSERT(avl_tree_key_int_eq(t, 4, &a, &g, &h, &d)); avl_tree_dtor(t); } void test_avl_tree_get() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 8); CU_ASSERT(avl_tree_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); void *value = NULL; CU_ASSERT_EQUAL(avl_tree_get(t, CDC_FROM_INT(10), &value), CDC_STATUS_NOT_FOUND); avl_tree_dtor(t); } void test_avl_tree_count() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 2); CU_ASSERT_EQUAL(avl_tree_count(t, a.first), 1); CU_ASSERT_EQUAL(avl_tree_count(t, b.first), 1); CU_ASSERT_EQUAL(avl_tree_count(t, CDC_FROM_INT(10)), 0); avl_tree_dtor(t); } void test_avl_tree_find() { avl_tree_t *t = NULL; avl_tree_iter_t it = CDC_INIT_STRUCT; avl_tree_iter_t it_end = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, CDC_END), CDC_STATUS_OK); avl_tree_find(t, a.first, &it); CU_ASSERT_EQUAL(avl_tree_iter_value(&it), a.second); avl_tree_find(t, b.first, &it); CU_ASSERT_EQUAL(avl_tree_iter_value(&it), b.second); avl_tree_find(t, g.first, &it); CU_ASSERT_EQUAL(avl_tree_iter_value(&it), g.second); avl_tree_find(t, h.first, &it); avl_tree_end(t, &it_end); CU_ASSERT(avl_tree_iter_is_eq(&it, &it_end)); avl_tree_dtor(t); } void test_avl_tree_clear() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 2); avl_tree_clear(t); CU_ASSERT(avl_tree_empty(t)); avl_tree_clear(t); CU_ASSERT(avl_tree_empty(t)); avl_tree_dtor(t); } void test_avl_tree_insert() { avl_tree_t *t = NULL; const int kCount = 100; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctor(&t, &info), CDC_STATUS_OK); for (int i = 0; i < kCount; ++i) { CU_ASSERT_EQUAL(avl_tree_insert(t, CDC_FROM_INT(i), CDC_FROM_INT(i), NULL), CDC_STATUS_OK); } CU_ASSERT_EQUAL(avl_tree_size(t), kCount); for (int i = 0; i < kCount; ++i) { void *val = NULL; CU_ASSERT_EQUAL(avl_tree_get(t, CDC_FROM_INT(i), &val), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(val), i); } avl_tree_dtor(t); } void test_avl_tree_insert_or_assign() { avl_tree_t *t = NULL; pair_avl_tree_iter_bool_t ret = CDC_INIT_STRUCT; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_insert_or_assign(t, a.first, a.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 1); CU_ASSERT_EQUAL(avl_tree_iter_value(&ret.first), a.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(avl_tree_insert_or_assign(t, a.first, b.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 1); CU_ASSERT_EQUAL(avl_tree_get(t, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, b.second); CU_ASSERT_EQUAL(avl_tree_iter_value(&ret.first), b.second); CU_ASSERT(!ret.second); CU_ASSERT_EQUAL(avl_tree_insert_or_assign(t, c.first, c.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 2); CU_ASSERT_EQUAL(avl_tree_iter_value(&ret.first), c.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(avl_tree_insert_or_assign(t, c.first, d.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 2); CU_ASSERT_EQUAL(avl_tree_get(t, c.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, d.second); CU_ASSERT_EQUAL(avl_tree_iter_value(&ret.first), d.second); CU_ASSERT(!ret.second); avl_tree_dtor(t); } void test_avl_tree_erase() { avl_tree_t *t = NULL; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 8); avl_tree_inorder_print_int(t->root); CU_ASSERT(avl_tree_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, a.first), 1); avl_tree_inorder_print_int(t->root); CU_ASSERT_EQUAL(avl_tree_get(t, a.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(avl_tree_key_int_eq(t, 7, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, h.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, h.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 6); CU_ASSERT(avl_tree_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, h.first), 0); CU_ASSERT_EQUAL(avl_tree_size(t), 6); CU_ASSERT(avl_tree_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, b.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, b.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 5); CU_ASSERT(avl_tree_key_int_eq(t, 5, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, c.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, c.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 4); CU_ASSERT(avl_tree_key_int_eq(t, 4, &d, &g, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, d.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, d.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 3); CU_ASSERT(avl_tree_key_int_eq(t, 3, &g, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, g.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, g.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 2); CU_ASSERT(avl_tree_key_int_eq(t, 2, &e, &f)); CU_ASSERT_EQUAL(avl_tree_erase(t, f.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, f.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(avl_tree_size(t), 1); CU_ASSERT(avl_tree_key_int_eq(t, 1, &e)); CU_ASSERT_EQUAL(avl_tree_erase(t, e.first), 1); CU_ASSERT_EQUAL(avl_tree_get(t, e.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(avl_tree_empty(t)); avl_tree_dtor(t); } void test_avl_tree_iterators() { avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(avl_tree_ctorl(&t, &info, &a, &b, &c, &d, &e, &f, &g, &h, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(avl_tree_size(t), 8); avl_tree_iter_t it1 = CDC_INIT_STRUCT; avl_tree_iter_t it2 = CDC_INIT_STRUCT; pair_t *arr[] = {&a, &b, &c, &d, &e, &f, &g, &h}; size_t i = 0; avl_tree_begin(t, &it1); avl_tree_end(t, &it2); for (; !avl_tree_iter_is_eq(&it1, &it2); avl_tree_iter_next(&it1)) { CU_ASSERT_EQUAL(avl_tree_iter_key(&it1), arr[i]->first) ++i; } CU_ASSERT_EQUAL(avl_tree_size(t), i); i = avl_tree_size(t) - 1; avl_tree_end(t, &it1); avl_tree_iter_prev(&it1); avl_tree_begin(t, &it2); for (; !avl_tree_iter_is_eq(&it1, &it2); avl_tree_iter_prev(&it1)) { CU_ASSERT_EQUAL(avl_tree_iter_key(&it1), arr[i]->first) --i; } CU_ASSERT_EQUAL(i, 0); avl_tree_begin(t, &it1); while (avl_tree_iter_has_next(&it1)) { CU_ASSERT_EQUAL(avl_tree_iter_key(&it1), arr[i]->first) ++i; avl_tree_iter_next(&it1); } CU_ASSERT_EQUAL(avl_tree_size(t), i); i = avl_tree_size(t) - 1; avl_tree_end(t, &it1); avl_tree_iter_prev(&it1); while (avl_tree_iter_has_prev(&it1)) { CU_ASSERT_EQUAL(avl_tree_iter_key(&it1), arr[i]->first); --i; avl_tree_iter_prev(&it1); } CU_ASSERT_EQUAL(i, 0); avl_tree_dtor(t); } void test_avl_tree_swap() { } void test_avl_tree_height() { size_t count = 100000; avl_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; avl_tree_ctor(&t, &info); for (size_t i = 0; i < count; ++i) { int val = rand(); if (avl_tree_insert(t, CDC_FROM_INT(val), NULL, NULL) != CDC_STATUS_OK) { CU_ASSERT(true); } } double experimental_height = cdc_tree_height(t->root); double theoretical_max_height = 1.44 * log2((double)count); printf( "\nExperimental avl tree heigth: %f, theoretical max avl tree heigth: " "%f, tree size: %zu\n", experimental_height, theoretical_max_height, count); CU_ASSERT(experimental_height <= theoretical_max_height); avl_tree_dtor(t); }
maksimandrianov/cdstructures
src/adapters/stack.c
<filename>src/adapters/stack.c // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/adapters/stack.h" stat_t stack_ctor(const sequence_table_t *table, cstack_t **s, data_info_t *info) { assert(table != NULL); assert(s != NULL); cstack_t *tmp = (cstack_t *)malloc(sizeof(cstack_t)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } tmp->table = table; stat_t ret = tmp->table->ctor(&tmp->container, info); if (ret != CDC_STATUS_OK) { free(tmp); return ret; } *s = tmp; return CDC_STATUS_OK; } stat_t stack_ctorl(const sequence_table_t *table, cstack_t **s, data_info_t *info, ...) { assert(table != NULL); assert(s != NULL); va_list args; va_start(args, info); stat_t ret = stack_ctorv(table, s, info, args); va_end(args); return ret; } stat_t stack_ctorv(const sequence_table_t *table, cstack_t **s, data_info_t *info, va_list args) { assert(table != NULL); assert(s != NULL); cstack_t *tmp = (cstack_t *)malloc(sizeof(cstack_t)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } tmp->table = table; stat_t ret = tmp->table->ctorv(&tmp->container, info, args); if (ret != CDC_STATUS_OK) { free(tmp); return ret; } *s = tmp; return ret; } void stack_dtor(cstack_t *s) { assert(s != NULL); s->table->dtor(s->container); free(s); } void stack_swap(cstack_t *a, cstack_t *b) { assert(a != NULL); assert(b != NULL); assert(a->table == b->table); CDC_SWAP(void *, a->container, b->container); }
maksimandrianov/cdstructures
tests/test-treap.c
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/casts.h" #include "cdcontainers/treap.h" #include "cdcontainers/tree-utils.h" #include <float.h> #include <math.h> #include <stdarg.h> #include <CUnit/Basic.h> CDC_MAKE_TREE_HEIGTH_FN(treap_node_t *) static pair_t a = {CDC_FROM_INT(0), CDC_FROM_INT(0)}; static pair_t b = {CDC_FROM_INT(1), CDC_FROM_INT(1)}; static pair_t c = {CDC_FROM_INT(2), CDC_FROM_INT(2)}; static pair_t d = {CDC_FROM_INT(3), CDC_FROM_INT(3)}; static pair_t e = {CDC_FROM_INT(4), CDC_FROM_INT(4)}; static pair_t f = {CDC_FROM_INT(5), CDC_FROM_INT(5)}; static pair_t g = {CDC_FROM_INT(6), CDC_FROM_INT(6)}; static pair_t h = {CDC_FROM_INT(7), CDC_FROM_INT(7)}; static int lt(const void *l, const void *r) { return CDC_TO_INT(l) < CDC_TO_INT(r); } static bool treap_key_int_eq(treap_t *t, size_t count, ...) { va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { pair_t *val = va_arg(args, pair_t *); void *tmp = NULL; if (treap_get(t, val->first, &tmp) != CDC_STATUS_OK || tmp != val->second) { va_end(args); return false; } } va_end(args); return true; } static inline void treap_inorder_print_int(treap_node_t *node) { if (node->left) { treap_inorder_print_int(node->left); } printf("%d ", CDC_TO_INT(node->key)); if (node->right) { treap_inorder_print_int(node->right); } } void test_treap_ctor() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT(treap_empty(t)); treap_dtor(t); } void test_treap_ctorl() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &g, &h, &d, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 4); CU_ASSERT(treap_key_int_eq(t, 4, &a, &g, &h, &d)); treap_dtor(t); } void test_treap_get() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 8); CU_ASSERT(treap_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); void *value = NULL; CU_ASSERT_EQUAL(treap_get(t, CDC_FROM_INT(10), &value), CDC_STATUS_NOT_FOUND); treap_dtor(t); } void test_treap_count() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 2); CU_ASSERT_EQUAL(treap_count(t, a.first), 1); CU_ASSERT_EQUAL(treap_count(t, b.first), 1); CU_ASSERT_EQUAL(treap_count(t, CDC_FROM_INT(10)), 0); treap_dtor(t); } void test_treap_find() { treap_t *t = NULL; treap_iter_t it = CDC_INIT_STRUCT; treap_iter_t it_end = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, &c, &d, &g, CDC_END), CDC_STATUS_OK); treap_find(t, a.first, &it); CU_ASSERT_EQUAL(treap_iter_value(&it), a.second); treap_find(t, b.first, &it); CU_ASSERT_EQUAL(treap_iter_value(&it), b.second); treap_find(t, g.first, &it); CU_ASSERT_EQUAL(treap_iter_value(&it), g.second); treap_find(t, h.first, &it); treap_end(t, &it_end); CU_ASSERT(treap_iter_is_eq(&it, &it_end)); treap_dtor(t); } void test_treap_clear() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 2); treap_clear(t); CU_ASSERT(treap_empty(t)); treap_clear(t); CU_ASSERT(treap_empty(t)); treap_dtor(t); } void test_treap_insert() { treap_t *t = NULL; const int kCount = 100; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctor(&t, &info), CDC_STATUS_OK); for (int i = 0; i < kCount; ++i) { CU_ASSERT_EQUAL(treap_insert(t, CDC_FROM_INT(i), CDC_FROM_INT(i), NULL), CDC_STATUS_OK); } CU_ASSERT_EQUAL(treap_size(t), kCount); for (int i = 0; i < kCount; ++i) { void *val = NULL; CU_ASSERT_EQUAL(treap_get(t, CDC_FROM_INT(i), &val), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(val), i); } treap_dtor(t); } void test_treap_insert_or_assign() { treap_t *t = NULL; pair_treap_iter_bool_t ret = CDC_INIT_STRUCT; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_insert_or_assign(t, a.first, a.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 1); CU_ASSERT_EQUAL(treap_iter_value(&ret.first), a.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(treap_insert_or_assign(t, a.first, b.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 1); CU_ASSERT_EQUAL(treap_get(t, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, b.second); CU_ASSERT_EQUAL(treap_iter_value(&ret.first), b.second); CU_ASSERT(!ret.second); CU_ASSERT_EQUAL(treap_insert_or_assign(t, c.first, c.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 2); CU_ASSERT_EQUAL(treap_iter_value(&ret.first), c.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(treap_insert_or_assign(t, c.first, d.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 2); CU_ASSERT_EQUAL(treap_get(t, c.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, d.second); CU_ASSERT_EQUAL(treap_iter_value(&ret.first), d.second); CU_ASSERT(!ret.second); treap_dtor(t); } void test_treap_erase() { treap_t *t = NULL; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 8); CU_ASSERT(treap_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, a.first), 1); CU_ASSERT_EQUAL(treap_get(t, a.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(treap_key_int_eq(t, 7, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, h.first), 1); CU_ASSERT_EQUAL(treap_get(t, h.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 6); CU_ASSERT(treap_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, h.first), 0); CU_ASSERT_EQUAL(treap_size(t), 6); CU_ASSERT(treap_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, b.first), 1); CU_ASSERT_EQUAL(treap_get(t, b.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 5); CU_ASSERT(treap_key_int_eq(t, 5, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, c.first), 1); CU_ASSERT_EQUAL(treap_get(t, c.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 4); CU_ASSERT(treap_key_int_eq(t, 4, &d, &g, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, d.first), 1); CU_ASSERT_EQUAL(treap_get(t, d.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 3); CU_ASSERT(treap_key_int_eq(t, 3, &g, &e, &f)); CU_ASSERT_EQUAL(treap_erase(t, f.first), 1); CU_ASSERT_EQUAL(treap_get(t, f.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 2); CU_ASSERT(treap_key_int_eq(t, 2, &g, &e)); CU_ASSERT_EQUAL(treap_erase(t, e.first), 1); CU_ASSERT_EQUAL(treap_get(t, e.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(treap_size(t), 1); CU_ASSERT(treap_key_int_eq(t, 1, &g)); CU_ASSERT_EQUAL(treap_erase(t, g.first), 1); CU_ASSERT_EQUAL(treap_get(t, g.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(treap_empty(t)); treap_dtor(t); } void test_treap_iterators() { treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(treap_ctorl(&t, &info, &a, &b, &c, &d, &e, &f, &g, &h, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(treap_size(t), 8); treap_iter_t it1 = CDC_INIT_STRUCT; treap_iter_t it2 = CDC_INIT_STRUCT; pair_t *arr[] = {&a, &b, &c, &d, &e, &f, &g, &h}; size_t i = 0; treap_begin(t, &it1); treap_end(t, &it2); for (; !treap_iter_is_eq(&it1, &it2); treap_iter_next(&it1)) { CU_ASSERT_EQUAL(treap_iter_key(&it1), arr[i]->first) ++i; } CU_ASSERT_EQUAL(treap_size(t), i); i = treap_size(t) - 1; treap_end(t, &it1); treap_iter_prev(&it1); treap_begin(t, &it2); for (; !treap_iter_is_eq(&it1, &it2); treap_iter_prev(&it1)) { CU_ASSERT_EQUAL(treap_iter_key(&it1), arr[i]->first) --i; } CU_ASSERT_EQUAL(i, 0); treap_begin(t, &it1); while (treap_iter_has_next(&it1)) { CU_ASSERT_EQUAL(treap_iter_key(&it1), arr[i]->first) ++i; treap_iter_next(&it1); } CU_ASSERT_EQUAL(treap_size(t), i); i = treap_size(t) - 1; treap_end(t, &it1); treap_iter_prev(&it1); while (treap_iter_has_prev(&it1)) { CU_ASSERT_EQUAL(treap_iter_key(&it1), arr[i]->first); --i; treap_iter_prev(&it1); } CU_ASSERT_EQUAL(i, 0); treap_dtor(t); } void test_treap_swap() { } void test_treap_height() { size_t count = 100000; treap_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; treap_ctor(&t, &info); for (size_t i = 0; i < count; ++i) { int val = rand(); if (treap_insert(t, CDC_FROM_INT(val), NULL, NULL) != CDC_STATUS_OK) { CU_ASSERT(true); } } double experimental_height = cdc_tree_height(t->root); printf("\nExperimental treap heigth: %f, tree size: %zu\n", experimental_height, count); treap_dtor(t); }
maksimandrianov/cdstructures
tests/test-list.c
<reponame>maksimandrianov/cdstructures<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include "cdcontainers/list.h" #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> static bool list_range_int_eq(list_t *l, size_t count, ...) { va_list args; stat_t ret; va_start(args, count); for (size_t i = 0; i < count; ++i) { void *val = NULL; if ((ret = list_at(l, i, &val)) != CDC_STATUS_OK) { return false; } int elem = va_arg(args, int); if (elem != CDC_TO_INT(val)) { return false; } } return list_size(l) == count; } static inline void list_range_int_print(list_t *l) { printf("\n"); for (size_t i = 0; i < list_size(l); ++i) { void *val = NULL; if (list_at(l, i, &val) == CDC_STATUS_OK) { printf("%d ", CDC_TO_INT(val)); } } printf("\n"); } static int lt(const void *l, const void *r) { return CDC_TO_INT(l) < CDC_TO_INT(r); } static int eq(const void *l, const void *r) { return CDC_TO_INT(l) == CDC_TO_INT(r); } static int is_eq_2(const void *v) { return CDC_TO_INT(v) == 2; } void test_list_ctor() { list_t *l = NULL; CU_ASSERT_EQUAL(list_ctor(&l, NULL), CDC_STATUS_OK); CU_ASSERT(list_empty(l)); list_dtor(l); } void test_list_ctorl() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 4); CU_ASSERT(list_range_int_eq(l, 4, a, b, c, d)); list_dtor(l); } void test_list_push_back() { list_t *l = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(list_ctor(&l, NULL), CDC_STATUS_OK); CU_ASSERT(list_empty(l)); CU_ASSERT_EQUAL(list_push_back(l, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT(list_range_int_eq(l, 1, a)); CU_ASSERT_EQUAL(list_push_back(l, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT(list_range_int_eq(l, 2, a, b)); CU_ASSERT_EQUAL(list_push_back(l, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT(list_range_int_eq(l, 3, a, b, c)); list_dtor(l); } void test_list_push_front() { list_t *l = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(list_ctor(&l, NULL), CDC_STATUS_OK); CU_ASSERT(list_empty(l)); CU_ASSERT_EQUAL(list_push_front(l, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT(list_range_int_eq(l, 1, a)); CU_ASSERT_EQUAL(list_push_front(l, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT(list_range_int_eq(l, 2, b, a)); CU_ASSERT_EQUAL(list_push_front(l, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT(list_range_int_eq(l, 3, c, b, a)); list_dtor(l); } void test_list_at() { list_t *l = NULL; int a = 0, b = 1, c = 2; void *elem = NULL; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_at(l, 0, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); CU_ASSERT_EQUAL(list_at(l, 1, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); CU_ASSERT_EQUAL(list_at(l, 2, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); size_t index = list_size(l) + 1; CU_ASSERT_EQUAL(list_at(l, index, &elem), CDC_STATUS_OUT_OF_RANGE); list_dtor(l); } void test_list_front() { list_t *l = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(list_front(l)), a); list_dtor(l); } void test_list_back() { list_t *l = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(list_back(l)), b); list_dtor(l); } void test_list_pop_back() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = list_back(l); list_pop_back(l); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); elem = list_back(l); list_pop_back(l); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = list_back(l); list_pop_back(l); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = list_back(l); list_pop_back(l); CU_ASSERT(list_empty(l)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); list_dtor(l); } void test_list_pop_front() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = list_front(l); list_pop_front(l); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); elem = list_front(l); list_pop_front(l); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = list_front(l); list_pop_front(l); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = list_front(l); list_pop_front(l); CU_ASSERT(list_empty(l)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); list_dtor(l); } void test_list_swap() { list_t *v = NULL; list_t *w = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_swap(v, w); CU_ASSERT_EQUAL(list_size(v), 2); CU_ASSERT(list_range_int_eq(v, 2, a, d)); CU_ASSERT_EQUAL(list_size(w), 4); CU_ASSERT(list_range_int_eq(w, 4, a, b, c, d)); list_dtor(v); list_dtor(w); } void test_list_insert() { list_t *l = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(list_ctor(&l, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_insert(l, 0, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT(list_range_int_eq(l, 1, a)); CU_ASSERT_EQUAL(list_insert(l, list_size(l), CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT(list_range_int_eq(l, 2, a, c)); CU_ASSERT_EQUAL(list_insert(l, 1, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT(list_range_int_eq(l, 3, a, b, c)); CU_ASSERT_EQUAL(list_insert(l, 1, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_size(l), 4); CU_ASSERT(list_range_int_eq(l, 4, a, c, b, c)); list_dtor(l); } void test_list_erase() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_erase(l, 0); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT(list_range_int_eq(l, 3, b, c, d)); list_erase(l, 1); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT(list_range_int_eq(l, 2, b, d)); list_erase(l, list_size(l) - 1); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT(list_range_int_eq(l, 1, b)); list_dtor(l); } void test_list_ierase() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; list_iter_t it = CDC_INIT_STRUCT; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_begin(l, &it); list_ierase(&it); CU_ASSERT_EQUAL(list_size(l), 3); CU_ASSERT(list_range_int_eq(l, 3, b, c, d)); list_begin(l, &it); list_iter_next(&it); list_ierase(&it); CU_ASSERT_EQUAL(list_size(l), 2); CU_ASSERT(list_range_int_eq(l, 2, b, d)); list_end(l, &it); list_iter_prev(&it); list_ierase(&it); CU_ASSERT_EQUAL(list_size(l), 1); CU_ASSERT(list_range_int_eq(l, 1, b)); list_dtor(l); } void test_list_clear() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_clear(l); CU_ASSERT(list_empty(l)); list_dtor(l); } void test_list_iterators() { list_t *l = NULL; list_iter_t it = CDC_INIT_STRUCT; list_iter_t ittmp = CDC_INIT_STRUCT; list_riter_t rit = CDC_INIT_STRUCT; list_riter_t rittmp = CDC_INIT_STRUCT; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_begin(l, &it); CU_ASSERT_EQUAL(list_iter_has_next(&it), true); CU_ASSERT_EQUAL(list_iter_has_prev(&it), false); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), a); list_riter_from(&it, &rit); list_rend(l, &rittmp); CU_ASSERT(list_riter_is_eq(&rittmp, &rit)); list_iter_next(&it); CU_ASSERT(list_iter_has_next(&it)); CU_ASSERT(list_iter_has_prev(&it)); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), b); list_riter_from(&it, &rit); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), a); list_iter_next(&it); CU_ASSERT(list_iter_has_next(&it)); CU_ASSERT(list_iter_has_prev(&it)); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), c); list_riter_from(&it, &rit); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), b); list_iter_next(&it); CU_ASSERT(!list_iter_has_next(&it)); CU_ASSERT(list_iter_has_prev(&it)); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), d); list_riter_from(&it, &rit); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), c); list_iter_next(&it); list_end(l, &ittmp); CU_ASSERT(list_iter_is_eq(&ittmp, &it)); list_riter_from(&it, &rit); list_rbegin(l, &rittmp); CU_ASSERT(list_riter_is_eq(&rittmp, &rit)); list_iter_prev(&it); CU_ASSERT(!list_iter_has_next(&it)); CU_ASSERT(list_iter_has_prev(&it)); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), d); list_dtor(l); } void test_list_reverse_iterators() { list_t *l = NULL; list_iter_t it = CDC_INIT_STRUCT; list_iter_t ittmp = CDC_INIT_STRUCT; list_riter_t rit = CDC_INIT_STRUCT; list_riter_t rittmp = CDC_INIT_STRUCT; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_rbegin(l, &rit); CU_ASSERT(list_riter_has_next(&rit)); CU_ASSERT(!list_riter_has_prev(&rit)); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), d); list_iter_from(&rit, &it); list_end(l, &ittmp); CU_ASSERT(list_iter_is_eq(&ittmp, &it)); list_riter_next(&rit); CU_ASSERT(list_riter_has_next(&rit)); CU_ASSERT(list_riter_has_prev(&rit)); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), c); list_iter_from(&rit, &it); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), d); list_riter_next(&rit); CU_ASSERT(list_riter_has_next(&rit)); CU_ASSERT(list_riter_has_prev(&rit)); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), b); list_iter_from(&rit, &it); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), c); list_riter_next(&rit); CU_ASSERT(!list_riter_has_next(&rit)); CU_ASSERT(list_riter_has_prev(&rit)); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), a); list_iter_from(&rit, &it); CU_ASSERT_EQUAL(CDC_TO_INT(list_iter_data(&it)), b); list_riter_next(&rit); list_rend(l, &rittmp); CU_ASSERT(list_riter_is_eq(&rittmp, &rit)); list_iter_from(&rit, &it); list_begin(l, &ittmp); CU_ASSERT(list_iter_is_eq(&ittmp, &it)); list_riter_prev(&rit); CU_ASSERT(!list_riter_has_next(&rit)); CU_ASSERT(list_riter_has_prev(&rit)); CU_ASSERT_EQUAL(CDC_TO_INT(list_riter_data(&rit)), a); list_dtor(l); } void test_list_splice() { list_t *l1 = NULL; list_t *l2 = NULL; list_iter_t current = CDC_INIT_STRUCT; list_iter_t first = CDC_INIT_STRUCT; list_iter_t last = CDC_INIT_STRUCT; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_begin(l1, &current); list_iter_next(&current); list_begin(l2, &first); list_iter_next(&first); list_end(l2, &last); list_iter_prev(&last); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 6); CU_ASSERT_EQUAL(list_size(l2), 2); CU_ASSERT(list_range_int_eq(l1, 6, a, b, c, b, c, d)); CU_ASSERT(list_range_int_eq(l2, 2, a, d)); list_begin(l2, &current); list_iter_next(&current); list_begin(l1, &first); list_end(l1, &last); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 0); CU_ASSERT_EQUAL(list_size(l2), 8); CU_ASSERT(list_range_int_eq(l2, 8, a, a, b, c, b, c, d, d)); list_end(l2, &last); list_iter_prev(&last); list_iter_prev(&last); list_iter_prev(&last); list_iter_prev(&last); list_begin(l1, &current); list_begin(l2, &first); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 4); CU_ASSERT_EQUAL(list_size(l2), 4); CU_ASSERT(list_range_int_eq(l1, 4, a, a, b, c)); CU_ASSERT(list_range_int_eq(l2, 4, b, c, d, d)); list_begin(l1, &current); list_begin(l2, &first); list_end(l2, &last); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, b, c, d, d, a, a, b, c)); list_end(l1, &last); list_iter_prev(&last); list_iter_prev(&last); list_iter_prev(&last); list_iter_prev(&last); list_begin(l2, &current); list_begin(l1, &first); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 4); CU_ASSERT_EQUAL(list_size(l2), 4); CU_ASSERT(list_range_int_eq(l1, 4, a, a, b, c)); CU_ASSERT(list_range_int_eq(l2, 4, b, c, d, d)); list_end(l1, &current); list_begin(l2, &first); list_end(l2, &last); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, a, b, c, b, c, d, d)); list_begin(l1, &first); list_iter_next(&first); list_iter_next(&first); list_iter_next(&first); list_iter_next(&first); list_begin(l2, &current); list_end(l1, &last); list_splice(&current, &first, &last); CU_ASSERT_EQUAL(list_size(l1), 4); CU_ASSERT_EQUAL(list_size(l2), 4); CU_ASSERT(list_range_int_eq(l1, 4, a, a, b, c)); CU_ASSERT(list_range_int_eq(l2, 4, b, c, d, d)); list_dtor(l1); list_dtor(l2); } void test_list_ssplice() { list_t *l1 = NULL; list_t *l2 = NULL; list_iter_t current = CDC_INIT_STRUCT; list_iter_t first = CDC_INIT_STRUCT; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_begin(l1, &current); list_iter_next(&current); list_begin(l2, &first); list_iter_next(&first); list_ssplice(&current, &first); CU_ASSERT_EQUAL(list_size(l1), 7); CU_ASSERT_EQUAL(list_size(l2), 1); CU_ASSERT(list_range_int_eq(l1, 7, a, b, c, d, b, c, d)); CU_ASSERT(list_range_int_eq(l2, 1, a)); list_begin(l1, &current); list_begin(l2, &first); list_ssplice(&current, &first); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, a, b, c, d, b, c, d)); list_dtor(l1); list_dtor(l2); } void test_list_lsplice() { list_t *l1 = NULL; list_t *l2 = NULL; list_iter_t current = CDC_INIT_STRUCT; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_begin(l1, &current); list_iter_next(&current); list_lsplice(&current, l2); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, a, b, c, d, b, c, d)); list_dtor(l1); list_dtor(l2); } void test_list_merge() { list_t *l1 = NULL; list_t *l2 = NULL; int a = 0, b = 1, c = 2, d = 3, e = 4, f = 5, g = 6, h = 7; CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_FROM_INT(e), CDC_FROM_INT(g), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(b), CDC_FROM_INT(d), CDC_FROM_INT(f), CDC_FROM_INT(h), CDC_END), CDC_STATUS_OK); list_cmerge(l1, l2, lt); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, b, c, d, e, f, g, h)); list_dtor(l1); list_dtor(l2); CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(e), CDC_FROM_INT(f), CDC_FROM_INT(g), CDC_FROM_INT(h), CDC_END), CDC_STATUS_OK); list_cmerge(l1, l2, lt); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, b, c, d, e, f, g, h)); list_dtor(l1); list_dtor(l2); CU_ASSERT_EQUAL(list_ctorl(&l1, NULL, CDC_FROM_INT(e), CDC_FROM_INT(f), CDC_FROM_INT(g), CDC_FROM_INT(h), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(list_ctorl(&l2, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_cmerge(l1, l2, lt); CU_ASSERT_EQUAL(list_size(l1), 8); CU_ASSERT_EQUAL(list_size(l2), 0); CU_ASSERT(list_range_int_eq(l1, 8, a, b, c, d, e, f, g, h)); list_dtor(l1); list_dtor(l2); } void test_list_erase_if() { list_t *l; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL( list_ctorl(&l, NULL, CDC_FROM_INT(c), CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(c), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); list_erase_if(l, is_eq_2); CU_ASSERT(list_range_int_eq(l, 3, a, b, d)); list_dtor(l); } void test_list_reverse() { list_t *l = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_reverse(l); CU_ASSERT(list_range_int_eq(l, 4, d, c, b, a)); list_dtor(l); } void test_list_unique() { list_t *l = NULL; int a = 2, b = 1; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_END), CDC_STATUS_OK); list_punique(l, eq); CU_ASSERT(list_range_int_eq(l, 1, a)); list_clear(l); list_punique(l, eq); list_dtor(l); CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(b), CDC_FROM_INT(a), CDC_END), CDC_STATUS_OK); list_punique(l, eq); CU_ASSERT(list_range_int_eq(l, 3, a, b, a)); list_dtor(l); CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); list_punique(l, eq); CU_ASSERT(list_range_int_eq(l, 2, a, b)); list_dtor(l); } void test_list_sort() { list_t *l = NULL; int a = 2, b = 1, c = 4, d = 3; CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); list_csort(l, lt); CU_ASSERT(list_range_int_eq(l, 4, b, a, d, c)); list_clear(l); list_csort(l, lt); list_dtor(l); CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_END), CDC_STATUS_OK); list_csort(l, lt); CU_ASSERT(list_range_int_eq(l, 1, a)); list_dtor(l); CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); list_csort(l, lt); CU_ASSERT(list_range_int_eq(l, 2, b, a)); list_dtor(l); CU_ASSERT_EQUAL(list_ctorl(&l, NULL, CDC_FROM_INT(c), CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); list_csort(l, lt); CU_ASSERT(list_range_int_eq(l, 3, b, a, c)); list_dtor(l); }
maksimandrianov/cdstructures
examples/map.c
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // Program to emulates the phone book. #define CDC_USE_SHORT_NAMES #include <cdcontainers/cdc.h> #include <stdio.h> #include <string.h> int str_lt(const void *lhs, const void *rhs) { return strcmp((const char *)lhs, (const char *)rhs) < 0; } int handle_error(map_t *phone_book) { map_dtor(phone_book); return EXIT_FAILURE; } void print_phone_book(map_t *phone_book) { map_iter_t iter = CDC_INIT_STRUCT; if (map_iter_ctor(phone_book, &iter) != CDC_STATUS_OK) { printf("Error map_iter_init.\n"); return; } map_begin(phone_book, &iter); while (map_iter_has_next(&iter)) { printf("%s - %s\n", (char *)map_iter_key(&iter), (char *)map_iter_value(&iter)); map_iter_next(&iter); } } int main(int argc, char **argv) { CDC_UNUSED(argc); CDC_UNUSED(argv); map_t *phone_book = NULL; data_info_t data_info = CDC_INIT_STRUCT; data_info.cmp = str_lt; pair_t Lilia_Friedman = {"<NAME>", "(892) 670-4739"}; pair_t Tariq_Beltran = {"<NAME>", "(489) 600-7575"}; pair_t Laiba_Juarez = {"<NAME>", "(303) 885-5692"}; pair_t Elliott_Mooney = {"<NAME>", "(945) 616-4482"}; // map based on avl tree if (map_ctorl(cdc_map_avl, &phone_book, &data_info, &Lilia_Friedman, &Tariq_Beltran, &Laiba_Juarez, &Elliott_Mooney, CDC_END) != CDC_STATUS_OK) { return EXIT_FAILURE; } printf("Phone book:\n"); print_phone_book(phone_book); if (map_insert(phone_book, "Zak Byers", "(551) 396-1880", NULL /* iterator */, NULL /* is_inserted */) != CDC_STATUS_OK) { return handle_error(phone_book); } printf("Phone book after adding Zak Byers:\n"); print_phone_book(phone_book); if (map_count(phone_book, "Tariq Beltran") != 0) { map_erase(phone_book, "Tariq Beltran"); } printf("Phone book after erasing Tariq Beltran:\n"); print_phone_book(phone_book); if (map_insert_or_assign(phone_book, "Zak Byers", "(555) 396-188", NULL /* iterator */, NULL /* is_inserted */) != CDC_STATUS_OK) { return handle_error(phone_book); } printf("Phone book after update phone of <NAME>:\n"); print_phone_book(phone_book); return EXIT_SUCCESS; }
maksimandrianov/cdstructures
include/cdcontainers/avl-tree.h
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_avl_tree is a struct and functions that provide an avl tree. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_avl_tree_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_avl_tree_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> /** * @defgroup cdc_avl_tree * @brief The cdc_avl_tree is a struct and functions that provide an avl tree. * @{ */ /** * @brief The cdc_avl_tree_node is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_avl_tree_node { struct cdc_avl_tree_node *parent; struct cdc_avl_tree_node *left; struct cdc_avl_tree_node *right; void *key; void *value; unsigned char height; }; /** * @brief The cdc_avl_tree is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_avl_tree { struct cdc_avl_tree_node *root; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_avl_tree_iter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_avl_tree_iter { struct cdc_avl_tree *container; struct cdc_avl_tree_node *prev; struct cdc_avl_tree_node *current; }; struct cdc_pair_avl_tree_iter { struct cdc_avl_tree_iter first; struct cdc_avl_tree_iter second; }; struct cdc_pair_avl_tree_iter_bool { struct cdc_avl_tree_iter first; bool second; }; // Base /** * @defgroup cdc_avl_tree_base Base * @{ */ /** * @brief Constructs an empty avl tree. * @param[out] t - cdc_avl_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_ctor(struct cdc_avl_tree **t, struct cdc_data_info *info); /** * @brief Constructs an avl tree, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_avl_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_avl_tree *tree = NULL; * cdc_pair value1 = {CDC_FROM_INT(1), CDC_FROM_INT(2)}; * cdc_pair value2 = {CDC_FROM_INT(3), CDC_FROM_INT(4)}; * ... * if (cdc_avl_tree_ctorl(&tree, info, &value1, &value2, CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_avl_tree_ctorl(struct cdc_avl_tree **t, struct cdc_data_info *info, ...); /** * @brief Constructs an avl tree, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_avl_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_ctorv(struct cdc_avl_tree **t, struct cdc_data_info *info, va_list args); /** * @brief Destroys the avl tree. * @param[in] t - cdc_avl_tree */ void cdc_avl_tree_dtor(struct cdc_avl_tree *t); /** @} */ // Lookup /** * @defgroup cdc_avl_tree_lookup Lookup * @{ */ /** * @brief Returns a value that is mapped to a key. If the key does * not exist, then NULL will return. * @param[in] t - cdc_avl_tree * @param[in] key - key of the element to find * @param[out] value - pinter to the value that is mapped to a key. * @return CDC_STATUS_OK if the key is found, CDC_STATUS_NOT_FOUND otherwise. */ enum cdc_stat cdc_avl_tree_get(struct cdc_avl_tree *t, void *key, void **value); /** * @brief Returns the number of elements with key that compares equal to the * specified argument key, which is either 1 or 0 since this container does not * allow duplicates. * @param[in] t - cdc_avl_tree * @param[in] key - key value of the elements to count * @return number of elements with key key, that is either 1 or 0. */ size_t cdc_avl_tree_count(struct cdc_avl_tree *t, void *key); /** * @brief Finds an element with key equivalent to key. * @param[in] t - cdc_avl_tree * @param[in] key - key value of the element to search for * @param[out] it - pointer will be recorded iterator to an element with key * equivalent to key. If no such element is found, past-the-end iterator is * returned. */ void cdc_avl_tree_find(struct cdc_avl_tree *t, void *key, struct cdc_avl_tree_iter *it); /** @} */ // Capacity /** * @defgroup cdc_avl_tree_capacity Capacity * @{ */ /** * @brief Returns the number of items in the avl_tree. * @param[in] t - cdc_avl_tree * @return the number of items in the avl_tree. */ static inline size_t cdc_avl_tree_size(struct cdc_avl_tree *t) { assert(t != NULL); return t->size; } /** * @brief Checks if the avl tree has no elements. * @param[in] t - cdc_avl_tree * @return true if the avl tree is empty, false otherwise. */ static inline bool cdc_avl_tree_empty(struct cdc_avl_tree *t) { assert(t != NULL); return t->size == 0; } /** @} */ // Modifiers /** * @defgroup cdc_avl_tree_modifiers Modifiers * @{ */ /** * @brief Removes all the elements from the avl_tree. * @param[in] t - cdc_avl_tree */ void cdc_avl_tree_clear(struct cdc_avl_tree *t); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_avl_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair consisting of an iterator to the inserted element (or to * the element that prevented the insertion) and a bool denoting whether the * insertion took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_insert(struct cdc_avl_tree *t, void *key, void *value, struct cdc_pair_avl_tree_iter_bool *ret); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_avl_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator to the inserted element (or to the element that * prevented the insertion). The pointer can be equal to NULL. * @param[out] inserted - bool denoting whether the insertion * took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_insert1(struct cdc_avl_tree *t, void *key, void *value, struct cdc_avl_tree_iter *it, bool *inserted); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_avl_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair. The bool component is true if the insertion took place and * false if the assignment took place. The iterator component is pointing at the * element that was inserted or updated. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_insert_or_assign(struct cdc_avl_tree *t, void *key, void *value, struct cdc_pair_avl_tree_iter_bool *ret); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_avl_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator is pointing at the element that was inserted or updated. * The pointer can be equal to NULL * @param[out] inserted - bool is true if the insertion took place and false if the * assignment took place. The pointer can be equal to NULL * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_avl_tree_insert_or_assign1(struct cdc_avl_tree *t, void *key, void *value, struct cdc_avl_tree_iter *it, bool *inserted); /** * @brief Removes the element (if one exists) with the key equivalent to key. * @param[in] t - cdc_avl_tree * @param[in] key - key value of the elements to remove * @return number of elements removed. */ size_t cdc_avl_tree_erase(struct cdc_avl_tree *t, void *key); /** * @brief Swaps avl_trees a and b. This operation is very fast and never fails. * @param[in, out] a - cdc_avl_tree * @param[in, out] b - cdc_avl_tree */ void cdc_avl_tree_swap(struct cdc_avl_tree *a, struct cdc_avl_tree *b); /** @} */ // Iterators /** * @defgroup cdc_avl_tree_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param[in] t - cdc_avl_tree * @param[out] it - cdc_avl_tree_iter */ void cdc_avl_tree_begin(struct cdc_avl_tree *t, struct cdc_avl_tree_iter *it); /** * @brief Initializes the iterator to the end. * @param[in] t - cdc_avl_tree * @param[out] it - cdc_avl_tree_iter */ void cdc_avl_tree_end(struct cdc_avl_tree *t, struct cdc_avl_tree_iter *it); /** @} */ // Iterators /** * @defgroup cdc_avl_tree_iter * @brief The cdc_avl_tree_iter is a struct and functions that provide an avl tree iterator. * @{ */ /** * @brief Advances the iterator to the next element in the avl tree. * @param[in] it - iterator */ void cdc_avl_tree_iter_next(struct cdc_avl_tree_iter *it); /** * @brief Advances the iterator to the previous element in the avl tree. * @param[in] it - iterator */ void cdc_avl_tree_iter_prev(struct cdc_avl_tree_iter *it); /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_avl_tree_iter_has_next(struct cdc_avl_tree_iter *it) { assert(it != NULL); return it->current != NULL; } /** * @brief Returns true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. */ static inline bool cdc_avl_tree_iter_has_prev(struct cdc_avl_tree_iter *it) { assert(it != NULL); return it->prev != NULL; } /** * @brief Returns an item's key. * @param[in] it - iterator * @return the item's key. */ static inline void *cdc_avl_tree_iter_key(struct cdc_avl_tree_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns an item's value. * @param[in] it - iterator * @return the item's value. */ static inline void *cdc_avl_tree_iter_value(struct cdc_avl_tree_iter *it) { assert(it != NULL); return it->current->value; } /** * @brief Returns a pair, where first - key, second - value. * @param[in] it - iterator * @return pair, where first - key, second - value. */ static inline struct cdc_pair cdc_avl_tree_iter_key_value(struct cdc_avl_tree_iter *it) { assert(it != NULL); struct cdc_pair pair = {it->prev->key, it->prev->value}; return pair; } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_avl_tree_iter_is_eq(struct cdc_avl_tree_iter *it1, struct cdc_avl_tree_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->prev == it2->prev && it1->current == it2->current; } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_avl_tree_node avl_tree_node_t; typedef struct cdc_avl_tree avl_tree_t; typedef struct cdc_avl_tree_iter avl_tree_iter_t; typedef struct cdc_pair_avl_tree_iter pair_avl_tree_iter_t; typedef struct cdc_pair_avl_tree_iter_bool pair_avl_tree_iter_bool_t; // Base #define avl_tree_ctor(...) cdc_avl_tree_ctor(__VA_ARGS__) #define avl_tree_ctorv(...) cdc_avl_tree_ctorv(__VA_ARGS__) #define avl_tree_ctorl(...) cdc_avl_tree_ctorl(__VA_ARGS__) #define avl_tree_dtor(...) cdc_avl_tree_dtor(__VA_ARGS__) // Lookup #define avl_tree_get(...) cdc_avl_tree_get(__VA_ARGS__) #define avl_tree_count(...) cdc_avl_tree_count(__VA_ARGS__) #define avl_tree_find(...) cdc_avl_tree_find(__VA_ARGS__) // Capacity #define avl_tree_size(...) cdc_avl_tree_size(__VA_ARGS__) #define avl_tree_empty(...) cdc_avl_tree_empty(__VA_ARGS__) // Modifiers #define avl_tree_clear(...) cdc_avl_tree_clear(__VA_ARGS__) #define avl_tree_insert(...) cdc_avl_tree_insert(__VA_ARGS__) #define avl_tree_insert1(...) cdc_avl_tree_insert1(__VA_ARGS__) #define avl_tree_insert_or_assign(...) cdc_avl_tree_insert_or_assign(__VA_ARGS__) #define avl_tree_insert_or_assign1(...) cdc_avl_tree_insert_or_assign1(__VA_ARGS__) #define avl_tree_erase(...) cdc_avl_tree_erase(__VA_ARGS__) #define avl_tree_swap(...) cdc_avl_tree_swap(__VA_ARGS__) // Iterators #define avl_tree_begin(...) cdc_avl_tree_begin(__VA_ARGS__) #define avl_tree_end(...) cdc_avl_tree_end(__VA_ARGS__) // Iterators #define avl_tree_iter_next(...) cdc_avl_tree_iter_next(__VA_ARGS__) #define avl_tree_iter_has_next(...) cdc_avl_tree_iter_has_next(__VA_ARGS__) #define avl_tree_iter_has_prev(...) cdc_avl_tree_iter_has_prev(__VA_ARGS__) #define avl_tree_iter_prev(...) cdc_avl_tree_iter_prev(__VA_ARGS__) #define avl_tree_iter_key(...) cdc_avl_tree_iter_key(__VA_ARGS__) #define avl_tree_iter_value(...) cdc_avl_tree_iter_value(__VA_ARGS__) #define avl_tree_iter_key_value(...) cdc_avl_tree_iter_key_value(__VA_ARGS__) #define avl_tree_iter_is_eq(...) cdc_avl_tree_iter_is_eq(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_avl_tree_H
maksimandrianov/cdstructures
include/cdcontainers/circular-array.h
<reponame>maksimandrianov/cdstructures<filename>include/cdcontainers/circular-array.h // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_circular_array is a struct and functions that provide a * circular array. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_CIRCULAR_ARRAY_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_CIRCULAR_ARRAY_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @defgroup cdc_circular_array * @brief The cdc_circular_array is a struct and functions that provide a circular array. * @{ */ /** * @brief The cdc_circular_array is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_circular_array { void **buffer; size_t head; size_t tail; size_t size; size_t capacity; struct cdc_data_info *dinfo; }; // Base /** * @defgroup cdc_circular_array_base Base * @{ */ /** * @brief Constructs an empty circular array. * @param[out] d - cdc_circular_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_circular_array_ctor(struct cdc_circular_array **d, struct cdc_data_info *info); /** * @brief Constructs a circular array, initialized by an variable number of pointers. * The last pointer must be CDC_END. * @param[out] d - cdc_circular_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_circular_array *carr = NULL; * if (cdc_circular_array_ctorl(&carr, NULL, CDC_FROM_INT(1), * CDC_FROM_INT(2), CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_circular_array_ctorl(struct cdc_circular_array **d, struct cdc_data_info *info, ...); /** * @brief Constructs a circular array, initialized by args. The last pointer must be CDC_END. * @param[out] d - cdc_circular_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_circular_array_ctorv(struct cdc_circular_array **d, struct cdc_data_info *info, va_list args); /** * @brief Destroys the circular array. * @param[in] d - cdc_circular_array */ void cdc_circular_array_dtor(struct cdc_circular_array *d); /** @} */ // Element access /** * @defgroup cdc_circular_array_element_access Element access * @{ */ /** * @brief Returns an element at index position in the circular array. * @param[in] d - cdc_circular_array * @param[in] index - index of an element to return * @return element from |index| position. */ static inline void *cdc_circular_array_get(struct cdc_circular_array *d, size_t index) { assert(d != NULL); assert(index < d->size); size_t real_index = (d->head + index) & (d->capacity - 1); return d->buffer[real_index]; } /** * @brief Writes to pointer an element from specified position in the circular array. * Bounds checking is performed. * @param[in] d - cdc_circular_array * @param[in] index - index of an element to write at elem * @param[out] elem - pointer where an element will be written * @return DC_STATUS_OK in a successful case or CDC_STATUS_OUT_OF_RANGE if the * index is incorrect. */ enum cdc_stat cdc_circular_array_at(struct cdc_circular_array *d, size_t index, void **elem); /** * @brief Returns a first element in the circular array. * @param[in] d - cdc_circular_array * @return first element in the circular array. */ static inline void *cdc_circular_array_front(struct cdc_circular_array *d) { assert(d != NULL); assert(d->size > 0); return d->buffer[d->head]; } /** * @brief Returns a last element in the circular array. * @param[in] d - cdc_circular_array * @return last element in the circular array. */ static inline void *cdc_circular_array_back(struct cdc_circular_array *d) { assert(d != NULL); assert(d->size > 0); size_t real_index = (d->tail - 1 + d->capacity) & (d->capacity - 1); return d->buffer[real_index]; } /** @} */ // Capacity /** * @defgroup cdc_circular_array_capacity Capacity * @{ */ /** * @brief Checks if the circular array has no elements. * @param[in] d - cdc_circular_array * @return true if the circular array is empty, false otherwise. */ static inline bool cdc_circular_array_empty(struct cdc_circular_array *d) { assert(d != NULL); return d->size == 0; } /** * @brief Returns the number of elements in the circular array. * @param[in] d - cdc_circular_array * @return the number of elements in the circular array. */ static inline size_t cdc_circular_array_size(struct cdc_circular_array *d) { assert(d != NULL); return d->size; } /** @} */ // Modifiers /** * @defgroup cdc_circular_array_modifiers Modifiers * @{ */ /** * @brief Sets an element at index position to the value. The function is not * called to free memory. * @param[in] d - cdc_circular_array * @param[in] index - index position where the value will be written * @param[in] value - value */ static inline void cdc_circular_array_set(struct cdc_circular_array *d, size_t index, void *value) { assert(d != NULL); assert(index < d->size); size_t real_index = (d->head + index) & (d->capacity - 1); d->buffer[real_index] = value; } /** * @brief Inserts value at |index| position in the circular array. If index is 0, the * value is prepended to the circular array. If index is cdc_circular_array_size(), the value is * appended to the circular array. * @param[in] d - cdc_circular_array * @param[in] index - index position where an element will be inserted * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_circular_array_insert(struct cdc_circular_array *d, size_t index, void *value); /** * @brief Removes an element at index position in the circular arrray. * @param[in] d - cdc_circular_array * @param[in] index - index position where an element will be removed */ void cdc_circular_array_erase(struct cdc_circular_array *d, size_t index); /** * @brief Removes all the elements from the circular array. * @param[in] d - cdc_circular_array */ void cdc_circular_array_clear(struct cdc_circular_array *d); /** * @brief Inserts an element at the end of the circular array. * @param[in] d - cdc_circular_array * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_circular_array_push_back(struct cdc_circular_array *d, void *value); /** * @brief Removes a last element in the circular array. * @param[in] d - cdc_circular_array */ void cdc_circular_array_pop_back(struct cdc_circular_array *d); /** * @brief Inserts an element at the beginning of the circular array. * @param[in] d - cdc_circular_array * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_circular_array_push_front(struct cdc_circular_array *d, void *value); /** * @brief Removes a first element in the circular array. * @param[in] d - cdc_circular_array */ void cdc_circular_array_pop_front(struct cdc_circular_array *d); /** * @brief Swaps circular arrays a and b. This operation is very fast and never * fails. * @param a - cdc_circular_array * @param b - cdc_circular_array */ void cdc_circular_array_swap(struct cdc_circular_array *a, struct cdc_circular_array *b); /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_circular_array circular_array_t; // Base #define circular_array_ctor(...) cdc_circular_array_ctor(__VA_ARGS__) #define circular_array_ctorl(...) cdc_circular_array_ctorl(__VA_ARGS__) #define circular_array_ctorv(...) cdc_circular_array_ctorv(__VA_ARGS__) #define circular_array_dtor(...) cdc_circular_array_dtor(__VA_ARGS__) // Element access #define circular_array_get(...) cdc_circular_array_get(__VA_ARGS__) #define circular_array_at(...) cdc_circular_array_at(__VA_ARGS__) #define circular_array_front(...) cdc_circular_array_front(__VA_ARGS__) #define circular_array_back(...) cdc_circular_array_back(__VA_ARGS__) // Capacity #define circular_array_empty(...) cdc_circular_array_empty(__VA_ARGS__) #define circular_array_size(...) cdc_circular_array_size(__VA_ARGS__) // Modifiers #define circular_array_set(...) cdc_circular_array_set(__VA_ARGS__) #define circular_array_insert(...) cdc_circular_array_insert(__VA_ARGS__) #define circular_array_erase(...) cdc_circular_array_erase(__VA_ARGS__) #define circular_array_clear(...) cdc_circular_array_clear(__VA_ARGS__) #define circular_array_push_back(...) cdc_circular_array_push_back(__VA_ARGS__) #define circular_array_pop_back(...) cdc_circular_array_pop_back(__VA_ARGS__) #define circular_array_push_front(...) cdc_circular_array_push_front(__VA_ARGS__) #define circular_array_pop_front(...) cdc_circular_array_pop_front(__VA_ARGS__) #define circular_array_swap(...) cdc_circular_array_swap(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_CIRCULAR_ARRAY_H
maksimandrianov/cdstructures
tests/test-circular-array.c
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/casts.h" #include "cdcontainers/circular-array.h" #include <assert.h> #include <float.h> #include <stdarg.h> #include <stdio.h> #include <CUnit/Basic.h> static bool circular_array_range_int_eq(circular_array_t *d, size_t count, ...) { assert(circular_array_size(d) >= count); va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { int elem = va_arg(args, int); stat_t ret; void *val = NULL; if ((ret = circular_array_at(d, i, &val)) != CDC_STATUS_OK || elem != CDC_TO_INT(val)) { return false; } } return true; } static inline void circular_array_range_int_print(circular_array_t *d) { void *val = NULL; for (size_t i = 0; i < circular_array_size(d); ++i) { if (circular_array_at(d, i, &val) == CDC_STATUS_OK) { printf("%d ", CDC_TO_INT(val)); } } printf("\n"); } void test_circular_array_ctor() { circular_array_t *d = NULL; CU_ASSERT_EQUAL(circular_array_ctor(&d, NULL), CDC_STATUS_OK); CU_ASSERT(circular_array_empty(d)); circular_array_dtor(d); } void test_circular_array_ctorl() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, a, b, c, d)); circular_array_dtor(arr); } void test_circular_array_push_back() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(circular_array_ctor(&arr, NULL), CDC_STATUS_OK); circular_array_push_back(arr, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(circular_array_size(arr), 1); CU_ASSERT(circular_array_range_int_eq(arr, 1, a)); circular_array_push_back(arr, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(circular_array_size(arr), 2); CU_ASSERT(circular_array_range_int_eq(arr, 1, a, b)); circular_array_push_back(arr, CDC_FROM_INT(c)); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT(circular_array_range_int_eq(arr, 3, a, b, c)); circular_array_push_back(arr, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, a, b, c, a)); circular_array_push_back(arr, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(circular_array_size(arr), 5); CU_ASSERT(circular_array_range_int_eq(arr, 5, a, b, c, a, b)); circular_array_dtor(arr); } void test_circular_array_push_front() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(circular_array_ctor(&arr, NULL), CDC_STATUS_OK); CU_ASSERT(circular_array_empty(arr)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 1); CU_ASSERT(circular_array_range_int_eq(arr, 1, a)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 2); CU_ASSERT(circular_array_range_int_eq(arr, 2, b, a)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT(circular_array_range_int_eq(arr, 3, c, b, a)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, a, c, b, a)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 5); CU_ASSERT(circular_array_range_int_eq(arr, 4, b, a, c, b, a)); circular_array_dtor(arr); } void test_circular_array_get() { circular_array_t *arr = NULL; int a = 0, b = 1; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_get(arr, 0)), a); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_get(arr, 1)), b); circular_array_dtor(arr); } void test_circular_array_at() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2; void *elem = NULL; CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_at(arr, 0, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); CU_ASSERT_EQUAL(circular_array_at(arr, 1, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); CU_ASSERT_EQUAL(circular_array_at(arr, 2, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); size_t index = circular_array_size(arr) + 1; CU_ASSERT_EQUAL(circular_array_at(arr, index, &elem), CDC_STATUS_OUT_OF_RANGE); circular_array_dtor(arr); } void test_circular_array_set() { circular_array_t *d = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(circular_array_ctorl(&d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); circular_array_set(d, 0, CDC_FROM_INT(b)); CU_ASSERT(circular_array_range_int_eq(d, 2, b, b)); circular_array_set(d, 1, CDC_FROM_INT(a)); CU_ASSERT(circular_array_range_int_eq(d, 2, b, a)); circular_array_dtor(d); } void test_circular_array_front() { circular_array_t *d = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(circular_array_ctorl(&d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_front(d)), a); CU_ASSERT_EQUAL(circular_array_push_front(d, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_front(d)), b); circular_array_dtor(d); } void test_circular_array_back() { circular_array_t *d = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(circular_array_ctorl(&d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_back(d)), b); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(circular_array_back(d)), a); circular_array_dtor(d); } void test_circular_array_pop_back() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = circular_array_back(arr); circular_array_pop_back(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); elem = circular_array_back(arr); circular_array_pop_back(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = circular_array_back(arr); circular_array_pop_back(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = circular_array_back(arr); circular_array_pop_back(arr); CU_ASSERT(circular_array_empty(arr)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); circular_array_dtor(arr); } void test_circular_array_pop_front() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = circular_array_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); elem = circular_array_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = circular_array_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = circular_array_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_size(arr), 0); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); circular_array_dtor(arr); } void test_circular_array_swap() { circular_array_t *v = NULL; circular_array_t *w = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(circular_array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_ctorl(&w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); circular_array_swap(v, w); CU_ASSERT_EQUAL(circular_array_size(v), 2); CU_ASSERT(circular_array_range_int_eq(v, 2, a, d)); CU_ASSERT_EQUAL(circular_array_size(w), 4); CU_ASSERT(circular_array_range_int_eq(w, 4, a, b, c, d)); circular_array_dtor(v); circular_array_dtor(w); } void test_circular_array_insert() { circular_array_t *arr = NULL; int a = 1, b = 2, insert_count = 100; int i1 = 3, i2 = 4, i3 = 5; int v0 = -1, v1 = 0, v2 = 1, v3 = 2, v4 = 3, v5 = 4, v6 = 5; { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_insert(arr, 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, v1, v2, v0, v3, v4, v5, v6)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); CU_ASSERT(circular_array_range_int_eq(arr, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v2, v0, v3, v4, v5, v6)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v4, v5, v6, v1, v2, v3)); CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, v4, v0, v5, v6, v1, v2, v3)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v5)), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v2, v3, v4, v5, v4, v5)); CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, v2, v0, v3, v4, v5, v4, v5)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT(circular_array_range_int_eq(arr, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr) - 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v2, v3, v4, v0, v5, v6)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); CU_ASSERT(circular_array_range_int_eq(arr, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr) - 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v2, v3, v4, v0, v5, v6)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v4, v5, v6, v1, v2, v3)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr) - 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, v4, v5, v6, v1, v2, v0, v3)); circular_array_dtor(arr); } { CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_END), CDC_STATUS_OK); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v6)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 6, v1, v3, v4, v5, v6, v5)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr) - 3, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, v1, v3, v4, v0, v5, v6, v5)); circular_array_dtor(arr); } CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_insert(arr, 0, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT(circular_array_range_int_eq(arr, 3, i1, a, b)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr), CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, i1, a, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, 2, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 5); CU_ASSERT(circular_array_range_int_eq(arr, 5, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 14, i3, i1, b, a, i3, i2, i1, b, a, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT( circular_array_range_int_eq(arr, 15, i3, a, i1, b, a, i3, i2, i1, b, a, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr) - 2, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT( circular_array_range_int_eq(arr, 16, i3, a, i1, b, a, i3, i2, i1, b, a, i1, a, i3, a, b, i2)); circular_array_clear(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(0)), CDC_STATUS_OK); for (int i = 0; i <= insert_count; ++i) { CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(i)), CDC_STATUS_OK); } CU_ASSERT_EQUAL(circular_array_get(arr, 0), CDC_FROM_INT(0)); for (int i = insert_count; i >= 0; --i) { CU_ASSERT_EQUAL(circular_array_get(arr, (size_t)(insert_count - i + 1)), CDC_FROM_INT(i)); } circular_array_dtor(arr); } void test_circular_array_erase() { circular_array_t *d = NULL; int v1 = 0, v2 = 1, v3 = 2, v4 = 3, v5 = 4, v6 = 5; { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_erase(d, 2); CU_ASSERT(circular_array_range_int_eq(d, 5, v1, v2, v4, v5, v6)); circular_array_dtor(d); } { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); CU_ASSERT(circular_array_range_int_eq(d, 5, v2, v3, v4, v5, v6)); circular_array_erase(d, 1); CU_ASSERT(circular_array_range_int_eq(d, 4, v2, v4, v5, v6)); circular_array_dtor(d); } { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(d, 6, v4, v5, v6, v1, v2, v3)); circular_array_erase(d, 1); CU_ASSERT(circular_array_range_int_eq(d, 5, v4, v6, v1, v2, v3)); circular_array_dtor(d); } { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(d, 6, v2, v3, v4, v5, v4, v5)); circular_array_erase(d, 1); CU_ASSERT(circular_array_range_int_eq(d, 5, v2, v4, v5, v4, v5)); circular_array_dtor(d); } { CU_ASSERT_EQUAL(circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT(circular_array_range_int_eq(d, 5, v2, v3, v4, v5, v6)); circular_array_erase(d, circular_array_size(d) - 2); CU_ASSERT(circular_array_range_int_eq(d, 4, v2, v3, v4, v6)); circular_array_dtor(d); } { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); CU_ASSERT(circular_array_range_int_eq(d, 5, v2, v3, v4, v5, v6)); circular_array_erase(d, circular_array_size(d) - 2); CU_ASSERT(circular_array_range_int_eq(d, 4, v2, v3, v4, v6)); circular_array_dtor(d); } { CU_ASSERT_EQUAL( circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(d, 6, v4, v5, v6, v1, v2, v3)); circular_array_erase(d, circular_array_size(d) - 2); CU_ASSERT(circular_array_range_int_eq(d, 5, v4, v5, v6, v1, v3)); circular_array_dtor(d); } { CU_ASSERT_EQUAL(circular_array_ctorl(&d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_END), CDC_STATUS_OK); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); circular_array_pop_front(d); CU_ASSERT_EQUAL(circular_array_push_front(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v6)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(d, 6, v1, v3, v4, v5, v6, v5)); circular_array_erase(d, circular_array_size(d) - 3); CU_ASSERT(circular_array_range_int_eq(d, 5, v1, v3, v4, v6, v5)); circular_array_dtor(d); } { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2, d = 3, erase_count = 100; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); circular_array_erase(arr, 2); CU_ASSERT_EQUAL(circular_array_size(arr), 6); CU_ASSERT(circular_array_range_int_eq(arr, 3, a, b, d, a, b, c)); circular_array_erase(arr, 4); CU_ASSERT_EQUAL(circular_array_size(arr), 5); CU_ASSERT(circular_array_range_int_eq(arr, 5, a, b, d, a, c)); circular_array_erase(arr, 0); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, b, d, a, c)); circular_array_erase(arr, circular_array_size(arr) - 1); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT(circular_array_range_int_eq(arr, 3, b, d, a)); circular_array_clear(arr); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 4, d, c, b, a)); circular_array_erase(arr, 1); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT(circular_array_range_int_eq(arr, 3, d, b, a)); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT(circular_array_range_int_eq(arr, 7, d, d, b, a, d, c, a)); circular_array_erase(arr, circular_array_size(arr) - 2); CU_ASSERT_EQUAL(circular_array_size(arr), 6); CU_ASSERT(circular_array_range_int_eq(arr, 6, d, d, b, a, d, a)); circular_array_clear(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(0)), CDC_STATUS_OK); for (int i = 0; i <= erase_count; ++i) { CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(i)), CDC_STATUS_OK); } for (int i = erase_count; i >= 0; --i) { circular_array_erase(arr, 1); } CU_ASSERT_EQUAL(circular_array_size(arr), 1); CU_ASSERT_EQUAL(circular_array_get(arr, 0), CDC_FROM_INT(0)); circular_array_dtor(arr); } } void test_circular_array_clear() { circular_array_t *arr = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); circular_array_clear(arr); CU_ASSERT(circular_array_empty(arr)); circular_array_dtor(arr); } void test_circular_array_pop_push() { circular_array_t *arr; int a = 1, b = 2, c = 3; int i1 = 3, i2 = 4, i3 = 5; CU_ASSERT_EQUAL( circular_array_ctorl(&arr, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 3); for (int i = 0; i < 5; ++i) { CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); circular_array_pop_back(arr); CU_ASSERT_EQUAL(circular_array_push_front(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); circular_array_pop_back(arr); } CU_ASSERT(circular_array_range_int_eq(arr, 3, b, a, b)); CU_ASSERT_EQUAL(circular_array_size(arr), 3); for (int i = 0; i < 5; ++i) { CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(a)), CDC_STATUS_OK); circular_array_pop_front(arr); CU_ASSERT_EQUAL(circular_array_push_back(arr, CDC_FROM_INT(b)), CDC_STATUS_OK); circular_array_pop_front(arr); } CU_ASSERT(circular_array_range_int_eq(arr, 3, b, a, b)); CU_ASSERT_EQUAL(circular_array_size(arr), 3); CU_ASSERT_EQUAL(circular_array_insert(arr, 0, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 4); CU_ASSERT(circular_array_range_int_eq(arr, 4, i1, b, a, b)); CU_ASSERT_EQUAL(circular_array_insert(arr, circular_array_size(arr), CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 5); CU_ASSERT(circular_array_range_int_eq(arr, 5, i1, b, a, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, 2, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 6); CU_ASSERT(circular_array_range_int_eq(arr, 6, i1, b, i3, a, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, 4, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 7); CU_ASSERT(circular_array_range_int_eq(arr, 7, i1, b, i3, a, i1, b, i2)); CU_ASSERT_EQUAL(circular_array_insert(arr, 1, CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(circular_array_size(arr), 8); CU_ASSERT(circular_array_range_int_eq(arr, 8, i1, i2, b, i3, a, i1, b, i2)); circular_array_dtor(arr); }
maksimandrianov/cdstructures
src/avl-tree.c
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/avl-tree.h" #include "cdcontainers/data-info.h" #include "cdcontainers/tree-utils.h" #include <stdint.h> #include <stdlib.h> #include <string.h> CDC_MAKE_FIND_NODE_FN(avl_tree_node_t *) CDC_MAKE_MIN_NODE_FN(avl_tree_node_t *) CDC_MAKE_MAX_NODE_FN(avl_tree_node_t *) CDC_MAKE_SUCCESSOR_FN(avl_tree_node_t *) CDC_MAKE_PREDECESSOR_FN(avl_tree_node_t *) static avl_tree_node_t *make_new_node(void *key, void *val) { avl_tree_node_t *node = (avl_tree_node_t *)malloc(sizeof(avl_tree_node_t)); if (!node) { return NULL; } node->key = key; node->value = val; node->height = 1; node->parent = NULL; node->left = NULL; node->right = NULL; return node; } static void free_node(avl_tree_t *t, avl_tree_node_t *node) { assert(t != NULL); if (CDC_HAS_DFREE(t->dinfo)) { pair_t pair = {node->key, node->value}; t->dinfo->dfree(&pair); } free(node); } static void free_avl_tree(avl_tree_t *t, avl_tree_node_t *root) { assert(t != NULL); if (root == NULL) { return; } free_avl_tree(t, root->left); free_avl_tree(t, root->right); free_node(t, root); } static unsigned char height(avl_tree_node_t *node) { return node ? node->height : 0; } static int height_diff(avl_tree_node_t *node) { return height(node->right) - height(node->left); } static void update_height(avl_tree_node_t *node) { unsigned char lhs = height(node->left); unsigned char rhs = height(node->right); node->height = CDC_MAX(lhs, rhs) + 1; } static void update_link(avl_tree_node_t *parent, avl_tree_node_t *old_child, avl_tree_node_t *new_child) { new_child->parent = parent; if (!parent) { return; } if (parent->left == old_child) { parent->left = new_child; } else { parent->right = new_child; } } static void unlink_list(avl_tree_node_t *parent, avl_tree_node_t *child) { if (!parent) { return; } if (parent->left == child) { parent->left = NULL; } else { parent->right = NULL; } } static avl_tree_node_t *rotate_right(avl_tree_node_t *node) { avl_tree_node_t *q = node->left; update_link(node->parent, node, q); node->left = q->right; if (node->left) { node->left->parent = node; } q->right = node; if (q->right) { q->right->parent = q; } update_height(node); update_height(q); return q; } static avl_tree_node_t *rotate_left(avl_tree_node_t *node) { avl_tree_node_t *q = node->right; update_link(node->parent, node, q); node->right = q->left; if (node->right) { node->right->parent = node; } q->left = node; if (q->left) { q->left->parent = q; } update_height(node); update_height(q); return q; } static avl_tree_node_t *balance(avl_tree_node_t *node) { while (node) { update_height(node); int diff = height_diff(node); if (diff == 2) { if (height_diff(node->right) < 0) { node->right = rotate_right(node->right); } node = rotate_left(node); } else if (diff == -2) { if (height_diff(node->left) > 0) { node->left = rotate_left(node->left); } node = rotate_right(node); } else { if (node->parent) { node = node->parent; } else { break; } } } return node; } static avl_tree_node_t *insert_unique(avl_tree_t *t, avl_tree_node_t *node, avl_tree_node_t *nearest) { if (t->root != NULL) { if (t->dinfo->cmp(node->key, nearest->key)) { nearest->left = node; } else { nearest->right = node; } node->parent = nearest; t->root = balance(nearest); } else { t->root = node; } ++t->size; return node; } static avl_tree_node_t *find_hint(avl_tree_node_t *node, void *key, cdc_binary_pred_fn_t compar) { while (node) { if (compar(key, node->key)) { if (node->left) { node = node->left; } else { break; } } else if (compar(node->key, key)) { if (node->right) { node = node->right; } else { break; } } else { break; } } return node; } static avl_tree_node_t *erase_node(avl_tree_t *t, avl_tree_node_t *node) { avl_tree_node_t *parent = NULL; if (node->left == NULL && node->right == NULL) { parent = node->parent; unlink_list(parent, node); } else if (node->right == NULL) { parent = node->parent; if (parent) { if (parent->left == node) { parent->left = node->left; parent->left->parent = parent; } else { parent->right = node->left; parent->right->parent = parent; } } else { parent = node->left; parent->parent = NULL; } } else if (node->left == NULL) { parent = node->parent; if (parent) { if (parent->right == node) { parent->right = node->right; parent->right->parent = parent; } else { parent->left = node->right; parent->left->parent = parent; } } else { parent = node->right; parent->parent = NULL; } } else { avl_tree_node_t *mnode = cdc_min_tree_node(node->right); CDC_SWAP(void *, node->value, mnode->value); CDC_SWAP(void *, node->key, mnode->key); parent = mnode->parent; if (parent == node) { parent->right = NULL; } else if (parent) { parent->left = mnode->right; if (mnode->right) { mnode->right->parent = parent; } } node = mnode; } free_node(t, node); return balance(parent); } static stat_t init_varg(avl_tree_t *t, va_list args) { pair_t *pair = NULL; while ((pair = va_arg(args, pair_t *)) != CDC_END) { stat_t stat = avl_tree_insert(t, pair->first, pair->second, NULL); if (stat != CDC_STATUS_OK) { return stat; } } return CDC_STATUS_OK; } stat_t avl_tree_ctor(avl_tree_t **t, data_info_t *info) { assert(t != NULL); assert(CDC_HAS_CMP(info)); avl_tree_t *tmp = (avl_tree_t *)calloc(sizeof(avl_tree_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } *t = tmp; return CDC_STATUS_OK; } stat_t avl_tree_ctorl(avl_tree_t **t, data_info_t *info, ...) { assert(t != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t stat = avl_tree_ctorv(t, info, args); va_end(args); return stat; } stat_t avl_tree_ctorv(avl_tree_t **t, data_info_t *info, va_list args) { assert(t != NULL); assert(CDC_HAS_CMP(info)); stat_t stat = avl_tree_ctor(t, info); if (stat != CDC_STATUS_OK) { return stat; } return init_varg(*t, args); } void avl_tree_dtor(avl_tree_t *t) { assert(t != NULL); free_avl_tree(t, t->root); di_shared_dtor(t->dinfo); free(t); } stat_t avl_tree_get(avl_tree_t *t, void *key, void **value) { assert(t != NULL); avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (node) { *value = node->value; return CDC_STATUS_OK; } return CDC_STATUS_NOT_FOUND; } size_t avl_tree_count(avl_tree_t *t, void *key) { assert(t != NULL); return (size_t)(cdc_find_tree_node(t->root, key, t->dinfo->cmp) != NULL); } void avl_tree_find(avl_tree_t *t, void *key, avl_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (!node) { avl_tree_end(t, it); return; } it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } stat_t avl_tree_insert(avl_tree_t *t, void *key, void *value, pair_avl_tree_iter_bool_t *ret) { assert(t != NULL); avl_tree_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return avl_tree_insert1(t, key, value, it, inserted); } stat_t avl_tree_insert1(avl_tree_t *t, void *key, void *value, avl_tree_iter_t *it, bool *inserted) { assert(t != NULL); avl_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp); bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key); if (!finded) { avl_tree_node_t *new_node = make_new_node(key, value); if (!new_node) { return CDC_STATUS_BAD_ALLOC; } node = insert_unique(t, new_node, node); } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } stat_t avl_tree_insert_or_assign(avl_tree_t *t, void *key, void *value, pair_avl_tree_iter_bool_t *ret) { assert(t != NULL); avl_tree_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return avl_tree_insert_or_assign1(t, key, value, it, inserted); } stat_t avl_tree_insert_or_assign1(avl_tree_t *t, void *key, void *value, avl_tree_iter_t *it, bool *inserted) { assert(t != NULL); avl_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp); bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key); if (!finded) { avl_tree_node_t *new_node = make_new_node(key, value); if (!new_node) { return CDC_STATUS_BAD_ALLOC; } node = insert_unique(t, new_node, node); } else { node->value = value; } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } size_t avl_tree_erase(avl_tree_t *t, void *key) { assert(t != NULL); avl_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (!node) { return 0; } t->root = erase_node(t, node); --t->size; return 1; } void avl_tree_clear(avl_tree_t *t) { assert(t != NULL); free_avl_tree(t, t->root); t->size = 0; t->root = NULL; } void avl_tree_swap(avl_tree_t *a, avl_tree_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(avl_tree_node_t *, a->root, b->root); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void avl_tree_begin(avl_tree_t *t, avl_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = cdc_min_tree_node(t->root); it->prev = NULL; } void avl_tree_end(avl_tree_t *t, avl_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = NULL; it->prev = cdc_max_tree_node(t->root); } void avl_tree_iter_next(avl_tree_iter_t *it) { assert(it != NULL); it->prev = it->current; it->current = cdc_tree_successor(it->current); } void avl_tree_iter_prev(avl_tree_iter_t *it) { assert(it != NULL); it->current = it->prev; it->prev = cdc_tree_predecessor(it->current); }
maksimandrianov/cdstructures
src/list.c
<filename>src/list.c // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/list.h" #include "cdcontainers/data-info.h" #include <stdint.h> #include <string.h> static list_node_t *make_new_node(void *val) { list_node_t *node = (list_node_t *)malloc(sizeof(list_node_t)); if (node) { node->data = val; } return node; } static void free_node(list_t *l, list_node_t *node) { assert(l != NULL); if (CDC_HAS_DFREE(l->dinfo)) { l->dinfo->dfree(node->data); } free(node); } static void free_nodes(list_t *l) { list_node_t *current = l->head; list_node_t *next = NULL; while (current) { next = current->next; free_node(l, current); current = next; }; } static stat_t insert_mid(list_t *l, list_node_t *n, void *value) { list_node_t *node = make_new_node(value); if (node == NULL) { return CDC_STATUS_BAD_ALLOC; } node->next = n; node->prev = n->prev; n->prev->next = node; n->prev = node; ++l->size; return CDC_STATUS_OK; } static stat_t insert(list_t *l, list_node_t *n, void *value) { if (n == l->head) { return list_push_front(l, value); } if (n == NULL) { return list_push_back(l, value); } return insert_mid(l, n, value); } static list_node_t *get_node(list_t *l, size_t index) { list_node_t *node = NULL; size_t i; if (index < l->size / 2) { i = 0; for (node = l->head; node != NULL && i < index; node = node->next, ++i) { /* empty */; } } else { i = l->size - 1; for (node = l->tail; node != NULL && i > index; node = node->prev, --i) { /* empty */; } } return i != index ? NULL : node; } static size_t distance(list_node_t *first, list_node_t *last) { size_t i = 0; for (; first != last; first = first->next, ++i) { /* empty */ } return i; } static void erase_node(list_t *l, list_node_t *node) { if (node == l->tail) { list_pop_back(l); } else if (node == l->head) { list_pop_front(l); } else { node->next->prev = node->prev; node->prev->next = node->next; free_node(l, node); --l->size; } } static void cmerge(list_node_t **ha, list_node_t **ta, list_node_t *hb, list_node_t *tb, cdc_binary_pred_fn_t compare) { list_node_t *a = *ha; list_node_t *b = hb; if (b == NULL) { return; } if (a == NULL) { *ha = hb; *ta = tb; return; } list_node_t *head = NULL; list_node_t *tail = NULL; while (b != NULL && a != NULL) { if (compare(a->data, b->data)) { if (head == NULL) { head = tail = a; } else { tail->next = a; a->prev = tail; tail = a; } a = a->next; } else { if (head == NULL) { head = tail = b; } else { tail->next = b; b->prev = tail; tail = b; } b = b->next; } } if (a == NULL) { tail->next = b; b->prev = tail; tail = tb; } else if (b == NULL) { tail->next = a; a->prev = tail; tail = *ta; } *ha = head; *ta = tail; } static void halve(list_node_t **ha, list_node_t **ta, list_node_t **hb, list_node_t **tb) { list_node_t *slow = *ha; list_node_t *fast = slow; if (slow == NULL || slow->next == NULL) { *hb = NULL; *tb = NULL; return; } while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } *hb = slow; *tb = *ta; *ta = slow->prev; (*ta)->next = NULL; (*hb)->prev = NULL; } static void merge_sort(list_node_t **head, list_node_t **tail, cdc_binary_pred_fn_t compare) { list_node_t *ha = *head; list_node_t *ta = *tail; if (ha == NULL || ha->next == NULL) { return; } list_node_t *hb = NULL; list_node_t *tb = NULL; halve(&ha, &ta, &hb, &tb); merge_sort(&ha, &ta, compare); merge_sort(&hb, &tb, compare); cmerge(&ha, &ta, hb, tb, compare); *head = ha; *tail = ta; } static stat_t init_varg(list_t *l, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t ret = list_push_back(l, elem); if (ret != CDC_STATUS_OK) { return ret; } } return CDC_STATUS_OK; } stat_t list_ctor(list_t **l, data_info_t *info) { assert(l != NULL); list_t *tmp = (list_t *)calloc(sizeof(list_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } *l = tmp; return CDC_STATUS_OK; } stat_t list_ctorl(list_t **l, data_info_t *info, ...) { assert(l != NULL); va_list args; va_start(args, info); stat_t ret = list_ctorv(l, info, args); va_end(args); return ret; } stat_t list_ctorv(list_t **l, data_info_t *info, va_list args) { assert(l != NULL); stat_t ret = list_ctor(l, info); if (ret != CDC_STATUS_OK) { return ret; } return init_varg(*l, args); } void list_dtor(list_t *l) { assert(l != NULL); free_nodes(l); di_shared_dtor(l->dinfo); free(l); } void list_set(list_t *l, size_t index, void *value) { assert(l != NULL); get_node(l, index)->data = value; } stat_t list_push_back(list_t *l, void *value) { assert(l != NULL); list_node_t *node = make_new_node(value); if (!node) { return CDC_STATUS_BAD_ALLOC; } if (l->tail == NULL) { node->prev = NULL; l->head = node; } else { node->prev = l->tail; l->tail->next = node; } node->next = NULL; l->tail = node; ++l->size; return CDC_STATUS_OK; } void list_pop_back(list_t *l) { assert(l != NULL); assert(l->tail != NULL); list_node_t *new_tail = l->tail->prev; free_node(l, l->tail); if (new_tail) { new_tail->next = NULL; l->tail = new_tail; } else { l->tail = NULL; l->head = NULL; } --l->size; } stat_t list_push_front(list_t *l, void *value) { assert(l != NULL); list_node_t *node = make_new_node(value); if (!node) { return CDC_STATUS_BAD_ALLOC; } if (l->head == NULL) { node->next = NULL; l->tail = node; } else { node->next = l->head; l->head->prev = node; } l->head = node; node->prev = NULL; ++l->size; return CDC_STATUS_OK; } void list_foreach(list_t *l, void (*cb)(void *)) { assert(l != NULL); assert(cb != NULL); list_node_t *node = l->head; while (node) { cb(node->data); node = node->next; } } stat_t list_at(list_t *l, size_t index, void **elem) { assert(l != NULL); assert(elem != NULL); if (index + 1 > l->size) { return CDC_STATUS_OUT_OF_RANGE; } list_node_t *node = get_node(l, index); *elem = node->data; return CDC_STATUS_OK; } void *list_get(list_t *l, size_t index) { assert(l != NULL); return get_node(l, index)->data; } void list_pop_front(list_t *l) { assert(l != NULL); assert(l->head != NULL); list_node_t *new_head = l->head->next; free_node(l, l->head); if (new_head) { new_head->prev = NULL; l->head = new_head; } else { l->tail = NULL; l->head = NULL; } --l->size; } stat_t list_insert(list_t *l, size_t index, void *value) { assert(l != NULL); assert(index <= l->size); list_node_t *node = get_node(l, index); return insert(l, node, value); } stat_t list_iinsert(list_iter_t *before, void *value) { assert(before != NULL); return insert(before->container, before->current, value); } void list_erase(list_t *l, size_t index) { assert(l != NULL); assert(index < l->size); list_node_t *node = get_node(l, index); erase_node(l, node); } void list_ierase(list_iter_t *pos) { assert(pos != NULL); erase_node(pos->container, pos->current); } void list_clear(list_t *l) { assert(l != NULL); free_nodes(l); l->size = 0; l->head = NULL; l->tail = NULL; } void list_swap(list_t *a, list_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(list_node_t *, a->head, b->head); CDC_SWAP(list_node_t *, a->tail, b->tail); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void list_splice(list_iter_t *position, list_iter_t *first, list_iter_t *last) { assert(position != NULL); assert(first != NULL); assert(last != NULL); list_iter_t prev_last = *last; size_t len = distance(first->current, last->current); list_iter_prev(&prev_last); if (first->current->prev) { if (last->current) { first->current->prev->next = last->current; last->current->prev = first->current->prev; } else { last->container->tail = first->current->prev; last->container->tail->next = NULL; } } else { if (last->current) { last->container->head = last->current; last->container->head->prev = NULL; } else { last->container->head = NULL; last->container->tail = NULL; } } if (position->current) { if (position->current->prev) { position->current->prev->next = first->current; first->current->prev = position->current->prev; position->current->prev = prev_last.current; prev_last.current->next = position->current; } else { position->container->head->prev = prev_last.current; prev_last.current->next = position->container->head; position->container->head = first->current; first->current->prev = NULL; } } else { if (position->container->tail) { position->container->tail->next = first->current; first->current->prev = position->container->tail; position->container->tail = prev_last.current; } else { first->current->prev = NULL; prev_last.current->next = NULL; position->container->head = first->current; position->container->tail = prev_last.current; } } position->container->size += len; first->container->size -= len; } void list_ssplice(list_iter_t *position, list_iter_t *first) { assert(position != NULL); assert(first != NULL); list_iter_t end; list_end(first->container, &end); list_splice(position, first, &end); } void list_lsplice(list_iter_t *position, list_t *other) { assert(position != NULL); assert(other != NULL); list_iter_t beg; list_iter_t end; list_begin(other, &beg); list_end(other, &end); list_splice(position, &beg, &end); } void list_cmerge(list_t *l, list_t *other, cdc_binary_pred_fn_t compare) { assert(l != NULL); assert(other != NULL); assert(compare != NULL); cmerge(&l->head, &l->tail, other->head, other->tail, compare); l->size = l->size + other->size; other->head = NULL; other->tail = NULL; other->size = 0; } void list_merge(list_t *l, list_t *other) { assert(l != NULL); assert(CDC_HAS_CMP(l->dinfo)); list_cmerge(l, other, l->dinfo->cmp); } void list_erase_if(list_t *l, cdc_unary_pred_fn_t pred) { assert(l != NULL); list_node_t *curr = l->head; list_node_t *tmp = NULL; while (curr) { if (pred(curr->data)) { tmp = curr->next; erase_node(l, curr); curr = tmp; if (curr == NULL) { return; } } else { curr = curr->next; } } } void list_reverse(list_t *l) { assert(l != NULL); list_node_t *curr = l->head; list_node_t *next = NULL; while (curr) { next = curr->next; CDC_SWAP(list_node_t *, curr->next, curr->prev); curr = next; } CDC_SWAP(list_node_t *, l->head, l->tail); } void list_punique(list_t *l, cdc_binary_pred_fn_t pred) { assert(l != NULL); list_node_t *curr = l->head; if (curr == NULL) { return; } list_node_t *next = curr->next; while (next) { if (pred(curr->data, next->data)) { erase_node(l, next); next = curr->next; } else { curr = next; next = next->next; } } } void list_unique(list_t *l) { assert(l != NULL); assert(CDC_HAS_CMP(l->dinfo)); list_punique(l, l->dinfo->cmp); } void list_csort(list_t *l, cdc_binary_pred_fn_t compare) { assert(l != NULL); assert(compare != NULL); merge_sort(&l->head, &l->tail, compare); } void list_sort(list_t *l) { assert(l != NULL); assert(CDC_HAS_CMP(l->dinfo)); list_csort(l, l->dinfo->cmp); }
maksimandrianov/cdstructures
include/cdcontainers/adapters/queue.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_queue is a struct and functions that provide a queue */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_QUEUE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_QUEUE_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <cdcontainers/tables/isequence.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_queue struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_queue { void *container; const struct cdc_sequence_table *table; }; /** * @brief Constructs an empty queue. * @param table - method table for a particular implementation * @param q - cdc_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_queue_ctor(const struct cdc_sequence_table *table, struct cdc_queue **q, struct cdc_data_info *info); /** * @brief Constructs a queue, initialized by an arbitrary number of pointers. * The last item must be NULL. * @param table - method table for a particular implementation * @param q - cdc_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_queue_ctorl(const struct cdc_sequence_table *table, struct cdc_queue **q, struct cdc_data_info *info, ...); /** * @brief Constructs a queue, initialized by args * The last item must be NULL. * @param table - method table for a particular implementation * @param q - cdc_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_queue_ctorv(const struct cdc_sequence_table *table, struct cdc_queue **q, struct cdc_data_info *info, va_list args); /** * @brief Destroys the queue. * @param q - cdc_queue */ void cdc_queue_dtor(struct cdc_queue *q); // Element access /** * @brief Returns pointer to the first element in the queue. This function * assumes that the queue isn't empty. * @param q - cdc_queue * @return pointer to the first element in the queue */ static inline void *cdc_queue_front(struct cdc_queue *q) { assert(q != NULL); return q->table->front(q->container); } /** * @brief Returns pointer to the last element in the queue. This function * assumes that the queue isn't empty. * @param q - cdc_queue * @return pointer to the last element in the queue */ static inline void *cdc_queue_back(struct cdc_queue *q) { assert(q != NULL); return q->table->back(q->container); } // Capacity /** * @brief Returns true if the queue has size 0; otherwise returns false. * @param q - cdc_queue * @return true if the list has size 0; otherwise returns false */ static inline bool cdc_queue_empty(struct cdc_queue *q) { assert(q != NULL); return q->table->empty(q->container); } /** * @brief Returns the number of items in the queue. * @param q - cdc_queue * @return size */ static inline size_t cdc_queue_size(struct cdc_queue *q) { assert(q != NULL); return q->table->size(q->container); } // Modifiers /** * @brief Adds value elem to the tail of the queue. * @param q - cdc_queue * @param elem * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_queue_push(struct cdc_queue *q, void *elem) { assert(q != NULL); return q->table->push_back(q->container, elem); } /** * @brief Removes the head item in the queue. This function assumes that the * queue isn't empty. * @param q - cdc_queue */ static inline void cdc_queue_pop(struct cdc_queue *q) { assert(q != NULL); q->table->pop_front(q->container); } /** * @brief Swaps queues a and b. This operation is very fast and never fails. * @param a - cdc_queue * @param b - cdc_queue */ void cdc_queue_swap(struct cdc_queue *a, struct cdc_queue *b); // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_queue queue_t; #define queue_ctor(...) cdc_queue_ctor(__VA_ARGS__) #define queue_ctorl(...) cdc_queue_ctorl(__VA_ARGS__) #define queue_ctorv(...) cdc_queue_ctorv(__VA_ARGS__) #define queue_dtor(...) cdc_queue_dtor(__VA_ARGS__) // Element access #define queue_front(...) cdc_queue_front(__VA_ARGS__) #define queue_back(...) cdc_queue_back(__VA_ARGS__) // Capacity #define queue_empty(...) cdc_queue_empty(__VA_ARGS__) #define queue_size(...) cdc_queue_size(__VA_ARGS__) // Modifiers #define queue_push(...) cdc_queue_push(__VA_ARGS__) #define queue_pop(...) cdc_queue_pop(__VA_ARGS__) #define queue_swap(...) cdc_queue_swap(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_QUEUE_H
maksimandrianov/cdstructures
include/cdcontainers/cdc.h
// The MIT License (MIT) // Copyright (c) 2019 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /*! @mainpage cdcontainers - data containers and data structures for C * * Library of data containers and data structures for C programming language. * The cdcontainers interface is similar to C ++ STL. The library contains the * following data containers: * - cdc_array - dynamic array. See array.h. * - cdc_list - doubly linked list. See list.h. * - cdc_circular_array - circular array. See circular-array.h. * - cdc_heap - binary heap. See heap.h. * - cdc_binomial_heap - binomial heap. See binomial-heap.h. * - cdc_pairing_heap - pairing heap. See pairing-heap.h. * - cdc_hash_table - hash table with collisions resolved by chaining. See * hash-table.h. * - cdc_avl_tree - avl tree. See avl-tree.h. * - cdc_splay_tree - splay tree. See splay-tree.h. * - cdc_treap - сartesian tree. See treap.h. * * and following adapters: * - cdc_deque (Can work with: cdc_array, cdc_list, cdc_circular_array). See * deque.h. * - cdc_stack (Can work with: cdc_array, cdc_list, cdc_circular_array). See * stack.h. * - cdc_queue (Can work with: cdc_array, cdc_list, cdc_circular_array). See * queue.h. * - cdc_priority_queue (Can work with: cdc_heap, cdc_binomial_heap, * cdc_pairing_heap). See priority-queue.h. * - cdc_map (Can work with: cdc_avl_tree, cdc_splay_tree, cdc_treap). See * map.h. * * Example usage array: * @include array.c * */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_CDC_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_CDC_H #include <cdcontainers/adapters/deque.h> #include <cdcontainers/adapters/map.h> #include <cdcontainers/adapters/priority-queue.h> #include <cdcontainers/adapters/queue.h> #include <cdcontainers/adapters/stack.h> #include <cdcontainers/array.h> #include <cdcontainers/avl-tree.h> #include <cdcontainers/binomial-heap.h> #include <cdcontainers/casts.h> #include <cdcontainers/circular-array.h> #include <cdcontainers/common.h> #include <cdcontainers/global.h> #include <cdcontainers/hash-table.h> #include <cdcontainers/hash.h> #include <cdcontainers/heap.h> #include <cdcontainers/list.h> #include <cdcontainers/pairing-heap.h> #include <cdcontainers/splay-tree.h> #include <cdcontainers/status.h> #include <cdcontainers/treap.h> #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_CDC_H
maksimandrianov/cdstructures
src/circular-array.c
<filename>src/circular-array.c // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/circular-array.h" #include "cdcontainers/data-info.h" #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #define CDC_CIRCULAR_ARRAY_MIN_CAPACITY 4 // must be pow 2 #define CDC_CIRCULAR_ARRAY_COPACITY_SHIFT 1 static size_t get_real_index(circular_array_t *d, size_t index) { return (d->head + index) & (d->capacity - 1); } static bool should_grow(circular_array_t *d) { return d->size == d->capacity - 1; } static stat_t reallocate(circular_array_t *d, size_t capacity) { if (capacity < CDC_CIRCULAR_ARRAY_MIN_CAPACITY) { capacity = CDC_CIRCULAR_ARRAY_MIN_CAPACITY; } if (capacity < d->size) { return CDC_STATUS_OK; } void **tmp = (void **)malloc(capacity * sizeof(void *)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (d->head > d->tail) { // _________________________________ // | 4 | 5 | 6 | . | . | 1 | 2 | 3 | // --------------------------------- size_t len = d->capacity - d->head; memcpy(tmp, d->buffer + d->head, len * sizeof(void *)); memcpy(tmp + len, d->buffer, d->tail * sizeof(void *)); } else { // _________________________________ // | 1 | 2 | 3 | 4 | 5 | 6 | . | . | // --------------------------------- memcpy(tmp, d->buffer + d->head, d->size * sizeof(void *)); } free(d->buffer); d->tail = d->size; d->head = 0; d->capacity = capacity; d->buffer = tmp; return CDC_STATUS_OK; } static stat_t grow(circular_array_t *d) { return reallocate(d, d->capacity << CDC_CIRCULAR_ARRAY_COPACITY_SHIFT); } static void free_data(circular_array_t *d) { if (!CDC_HAS_DFREE(d->dinfo)) { return; } for (size_t i = 0; i < d->size; ++i) { size_t real_index = get_real_index(d, i); d->dinfo->dfree(d->buffer[real_index]); } } static stat_t init_varg(circular_array_t *d, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t stat = circular_array_push_back(d, elem); if (stat != CDC_STATUS_OK) { return stat; } } return CDC_STATUS_OK; } stat_t circular_array_ctor(circular_array_t **d, data_info_t *info) { assert(d != NULL); circular_array_t *tmp = (circular_array_t *)calloc(sizeof(circular_array_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } stat_t ret = CDC_STATUS_OK; if (info && !(tmp->dinfo = di_shared_ctorc(info))) { ret = CDC_STATUS_BAD_ALLOC; goto free_di; } ret = reallocate(tmp, CDC_CIRCULAR_ARRAY_MIN_CAPACITY); if (ret != CDC_STATUS_OK) { goto free_circular_array; } *d = tmp; return ret; free_di: di_shared_dtor(tmp->dinfo); free_circular_array: free(tmp); return ret; } stat_t circular_array_ctorl(circular_array_t **d, data_info_t *info, ...) { assert(d != NULL); va_list args; va_start(args, info); stat_t stat = circular_array_ctorv(d, info, args); va_end(args); return stat; } stat_t circular_array_ctorv(circular_array_t **d, data_info_t *info, va_list args) { assert(d != NULL); stat_t stat = circular_array_ctor(d, info); if (stat != CDC_STATUS_OK) { return stat; } return init_varg(*d, args); } void circular_array_dtor(circular_array_t *d) { assert(d != NULL); free_data(d); free(d->buffer); di_shared_dtor(d->dinfo); free(d); } stat_t circular_array_at(circular_array_t *d, size_t index, void **elem) { assert(d != NULL); assert(elem != NULL); if (index > d->size) { return CDC_STATUS_OUT_OF_RANGE; } size_t real_index = get_real_index(d, index); *elem = d->buffer[real_index]; return CDC_STATUS_OK; } stat_t circular_array_insert(circular_array_t *d, size_t index, void *value) { assert(d != NULL); assert(index <= d->size); if (index == 0) { return circular_array_push_front(d, value); } if (index == d->size) { return circular_array_push_back(d, value); } if (should_grow(d)) { stat_t stat = grow(d); if (stat != CDC_STATUS_OK) { return stat; } } size_t real_index = get_real_index(d, index); size_t mcapacity = d->capacity - 1; if (index < d->size / 2) { // New head. if (d->head < d->tail) { if (d->head == 0) { // _________________________________ // | 1 | 2 | 3 | 4 | 5 | 6 | . | . | // --------------------------------- // <---------x d->buffer[d->capacity - 1] = d->buffer[0]; memmove(d->buffer, d->buffer + 1, (real_index - d->head - 1) * sizeof(void *)); } else { // _________________________________ // | . | 1 | 2 | 3 | 4 | 5 | 6 | . | // --------------------------------- // <--------x void **start = d->buffer + d->head; memmove(start - 1, start, (real_index - d->head) * sizeof(void *)); } } else { if (real_index > d->head) { // _________________________________ // | 4 | 5 | 6 | . | . | 1 | 2 | 3 | // --------------------------------- // <-------------------------x void **start = d->buffer + d->head; memmove(start - 1, start, (real_index - d->head) * sizeof(void *)); } else { // _________________________________ // | 2 | 3 | 4 | 5 | 6 | . | . | 1 | // --------------------------------- // <-----x void **start = d->buffer + d->head; memmove(start - 1, start, (d->capacity - d->head) * sizeof(void *)); d->buffer[d->capacity - 1] = d->buffer[0]; memmove(d->buffer, d->buffer + 1, real_index * sizeof(void *)); } } real_index = (real_index + mcapacity) & mcapacity; d->head = (d->head + mcapacity) & mcapacity; } else { // New tail. if (d->head < d->tail) { if (d->tail + 1 == d->capacity) { // _________________________________ // | . | . | 1 | 2 | 3 | 4 | 5 | 6 | // --------------------------------- // x-------> d->buffer[0] = d->buffer[d->capacity - 1]; } // ______________________________________ // | . | 1 | 2 | 3 | 4 | 5 | 6 | . or 7 | // -------------------------------------- // x-----------> void **start = d->buffer + real_index; memmove(start + 1, start, (d->tail - real_index) * sizeof(void *)); } else { if (real_index < d->tail) { // _________________________________ // | 4 | 5 | 6 | . | . | 1 | 2 | 3 | // --------------------------------- // x-------> void **start = d->buffer + real_index; memmove(start + 1, start, (d->tail - real_index) * sizeof(void *)); } else { // _________________________________ // | 6 | . | . | 1 | 2 | 3 | 4 | 5 | // --------------------------------- // x----> memmove(d->buffer + 1, d->buffer, d->tail * sizeof(void *)); d->buffer[0] = d->buffer[d->capacity - 1]; void **start = d->buffer + real_index; memmove(start + 1, start, (d->capacity - real_index - 1) * sizeof(void *)); } } d->tail = (d->tail + 1) & mcapacity; } d->buffer[real_index] = value; ++d->size; return CDC_STATUS_OK; } void circular_array_erase(circular_array_t *d, size_t index) { assert(d != NULL); assert(index < d->size); if (index == 0) { circular_array_pop_front(d); return; } if (index + 1 == d->size) { circular_array_pop_back(d); return; } size_t real_index = get_real_index(d, index); if (CDC_HAS_DFREE(d->dinfo)) { d->dinfo->dfree(d->buffer[real_index]); } size_t mcapacity = d->capacity - 1; if (index < d->size / 2) { // New head. if (d->head < d->tail) { // _________________________________ // | 1 | 2 | 3 | 4 | 5 | 6 | . | . | // --------------------------------- // ----->x void **start = d->buffer + d->head; memmove(start + 1, start, (real_index - d->head) * sizeof(void *)); } else { if (real_index > d->head) { // _________________________________ // | 4 | 5 | 6 | . | . | 1 | 2 | 3 | // --------------------------------- // ----->x void **start = d->buffer + d->head; memmove(start + 1, start, (real_index - d->head) * sizeof(void *)); } else { // _________________________________ // | 2 | 3 | 4 | 5 | 6 | . | . | 1 | // --------------------------------- // ----->x memmove(d->buffer + 1, d->buffer, real_index * sizeof(void *)); d->buffer[0] = d->buffer[d->capacity - 1]; void **start = d->buffer + d->head; memmove(start + 1, start, (mcapacity - d->head) * sizeof(void *)); } } d->head = (d->head + 1) & mcapacity; } else { // New tail. if (d->head < d->tail) { // _________________________________ // | . | . | 1 | 2 | 3 | 4 | 5 | 6 | // --------------------------------- // x<-------- void **start = d->buffer + real_index; memmove(start, start + 1, (d->tail - real_index) * sizeof(void *)); } else { if (real_index < d->tail) { // _________________________________ // | 4 | 5 | 6 | . | . | 1 | 2 | 3 | // --------------------------------- // x<------- void **start = d->buffer + real_index; memmove(start, start + 1, (d->tail - real_index) * sizeof(void *)); } else { // _________________________________ // | 6 | . | . | 1 | 2 | 3 | 4 | 5 | // --------------------------------- // x<---- void **start = d->buffer + real_index; memmove(start, start + 1, (mcapacity - real_index) * sizeof(void *)); d->buffer[d->capacity - 1] = d->buffer[0]; memmove(d->buffer, d->buffer + 1, d->tail * sizeof(void *)); } } d->tail = (d->tail + mcapacity) & mcapacity; } --d->size; } void circular_array_clear(circular_array_t *d) { assert(d != NULL); free_data(d); d->tail = 0; d->head = 0; d->size = 0; } stat_t circular_array_push_back(circular_array_t *d, void *value) { assert(d != NULL); if (should_grow(d)) { stat_t stat = grow(d); if (stat != CDC_STATUS_OK) { return stat; } } d->buffer[d->tail] = value; d->tail = (d->tail + 1) & (d->capacity - 1); ++d->size; return CDC_STATUS_OK; } void circular_array_pop_back(circular_array_t *d) { assert(d != NULL); assert(d->size > 0); if (CDC_HAS_DFREE(d->dinfo)) { d->dinfo->dfree(d->buffer[d->tail]); } d->tail = (d->tail + d->capacity - 1) & (d->capacity - 1); --d->size; } stat_t circular_array_push_front(circular_array_t *d, void *value) { assert(d != NULL); if (should_grow(d)) { stat_t stat = grow(d); if (stat != CDC_STATUS_OK) { return stat; } } size_t new_head = (d->head + d->capacity - 1) & (d->capacity - 1); d->buffer[new_head] = value; d->head = new_head; ++d->size; return CDC_STATUS_OK; } void circular_array_pop_front(circular_array_t *d) { assert(d != NULL); assert(d->size > 0); if (CDC_HAS_DFREE(d->dinfo)) { d->dinfo->dfree(d->buffer[d->head]); } d->head = (d->head + 1) & (d->capacity - 1); --d->size; } void circular_array_swap(circular_array_t *a, circular_array_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(size_t, a->capacity, b->capacity); CDC_SWAP(size_t, a->head, b->head); CDC_SWAP(size_t, a->tail, b->tail); CDC_SWAP(void **, a->buffer, b->buffer); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); }
maksimandrianov/cdstructures
src/pairing-heap.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/pairing-heap.h" #include "cdcontainers/data-info.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> static void free_node(pairing_heap_t *h, pairing_heap_node_t *node) { if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(node->key); } free(node); } static void free_heap(pairing_heap_t *h, pairing_heap_node_t *root) { while (root) { free_heap(h, root->child); pairing_heap_node_t *tmp = root->sibling; free_node(h, root); root = tmp; } } static bool is_heap(pairing_heap_node_t *root, cdc_binary_pred_fn_t compar) { while (root) { if (!is_heap(root->child, compar) || (root->parent && compar(root->key, root->parent->key))) { return false; } root = root->sibling; } return true; } static void link(pairing_heap_node_t *a, pairing_heap_node_t *broot) { a->parent = broot; a->sibling = broot->child; broot->child = a; } static pairing_heap_node_t *meld(pairing_heap_node_t *a, pairing_heap_node_t *b, cdc_binary_pred_fn_t compare) { if (a == NULL) { return b; } if (b == NULL) { return a; } if (compare(a->key, b->key)) { CDC_SWAP(pairing_heap_node_t *, a, b); } link(a, b); return b; } static pairing_heap_node_t *two_pass_meld(pairing_heap_node_t *root, cdc_binary_pred_fn_t compare) { if (root == NULL || root->sibling == NULL) { return root; } pairing_heap_node_t *a = root; pairing_heap_node_t *b = root->sibling; pairing_heap_node_t *c = root->sibling->sibling; a->parent = NULL; a->sibling = NULL; b->parent = NULL; b->sibling = NULL; return meld(meld(a, b, compare), two_pass_meld(c, compare), compare); } static pairing_heap_node_t *decrease_key(pairing_heap_t *h, pairing_heap_node_t *pos, void *key) { pairing_heap_node_t *node = pos; if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(node->key); } node->key = key; pairing_heap_node_t *p = node->parent; while (p != NULL && h->dinfo->cmp(node->key, p->key)) { CDC_SWAP(void *, node->key, p->key); node = p; p = node->parent; } return node; } static pairing_heap_node_t *increase_key(pairing_heap_t *h, pairing_heap_node_t *pos, void *key) { if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(pos->key); } pairing_heap_node_t *ch = pos->child; pos->key = key; while (ch != NULL) { if (h->dinfo->cmp(ch->key, pos->key)) { pairing_heap_node_t *t = ch; while (ch->sibling != NULL) { if (h->dinfo->cmp(ch->sibling->key, t->key)) { t = ch->sibling; } ch = ch->sibling; } CDC_SWAP(void *, t->key, pos->key); pos = t; ch = pos->child; } else { ch = ch->sibling; } } return pos; } static stat_t init_varg(pairing_heap_t *h, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t ret = pairing_heap_insert(h, elem); if (ret != CDC_STATUS_OK) { return ret; } } return CDC_STATUS_OK; } stat_t pairing_heap_ctor(pairing_heap_t **h, data_info_t *info) { assert(h != NULL); assert(CDC_HAS_CMP(info)); pairing_heap_t *tmp = (pairing_heap_t *)calloc(sizeof(pairing_heap_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } *h = tmp; return CDC_STATUS_OK; } stat_t pairing_heap_ctorl(pairing_heap_t **h, data_info_t *info, ...) { assert(h != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t ret = pairing_heap_ctorv(h, info, args); va_end(args); return ret; } stat_t pairing_heap_ctorv(pairing_heap_t **h, data_info_t *info, va_list args) { assert(h != NULL); assert(CDC_HAS_CMP(info)); stat_t ret = pairing_heap_ctor(h, info); if (ret != CDC_STATUS_OK) { return ret; } return init_varg(*h, args); } void pairing_heap_dtor(pairing_heap_t *h) { assert(h != NULL); free_heap(h, h->root); di_shared_dtor(h->dinfo); free(h); } stat_t pairing_heap_extract_top(pairing_heap_t *h) { assert(h != NULL); pairing_heap_node_t *node = h->root; h->root = two_pass_meld(h->root->child, h->dinfo->cmp); free_node(h, node); --h->size; return CDC_STATUS_OK; } stat_t pairing_heap_riinsert(pairing_heap_t *h, void *key, pairing_heap_iter_t *ret) { assert(h != NULL); pairing_heap_node_t *root = (pairing_heap_node_t *)calloc(sizeof(pairing_heap_node_t), 1); if (!root) { return CDC_STATUS_BAD_ALLOC; } root->key = key; h->root = meld(h->root, root, h->dinfo->cmp); ++h->size; if (ret) { ret->container = h; ret->current = root; } return CDC_STATUS_OK; } void pairing_heap_change_key(pairing_heap_t *h, pairing_heap_iter_t *pos, void *key) { assert(false); // assert(h != NULL); // assert(pos != NULL); // assert(h == pos->container); // pairing_heap_node_t *node; // pairing_heap_node_t *curr = pos->current; // if (h->compar(key, curr->key)) // node = decrease_key(h, curr, key); // else // node = increase_key(h, curr, key); // pos->current = node; } void pairing_heap_clear(pairing_heap_t *h) { assert(h != NULL); free_heap(h, h->root); h->size = 0; h->root = NULL; } void pairing_heap_swap(pairing_heap_t *a, pairing_heap_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(pairing_heap_node_t *, a->root, b->root); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void pairing_heap_merge(pairing_heap_t *h, pairing_heap_t *other) { assert(h); assert(other); h->root = meld(h->root, other->root, h->dinfo->cmp); h->size += other->size; other->size = 0; other->root = NULL; } bool pairing_heap_is_heap(pairing_heap_t *h) { assert(h != NULL); return is_heap(h->root, h->dinfo->cmp); }
maksimandrianov/cdstructures
src/array.c
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/array.h" #include "cdcontainers/data-info.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define ARRAY_MIN_CAPACITY 4 #define ARRAY_COPACITY_EXP 2.0f static bool should_grow(array_t *v) { return v->size == v->capacity; } static stat_t reallocate(array_t *v, size_t capacity) { if (capacity < ARRAY_MIN_CAPACITY) { capacity = ARRAY_MIN_CAPACITY; } if (capacity < v->size) { return CDC_STATUS_OK; } void **tmp = (void **)malloc(capacity * sizeof(void *)); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } memcpy(tmp, v->buffer, v->size * sizeof(void *)); free(v->buffer); v->capacity = capacity; v->buffer = tmp; return CDC_STATUS_OK; } static stat_t grow(array_t *v) { return reallocate(v, (size_t)(v->capacity * ARRAY_COPACITY_EXP)); } static void free_data(array_t *v) { if (CDC_HAS_DFREE(v->dinfo)) { for (size_t i = 0; i < v->size; ++i) { v->dinfo->dfree(v->buffer[i]); } } } static void free_buffer(array_t *v) { free_data(v); free(v->buffer); v->buffer = NULL; } static void move_left(array_t *v, size_t index) { size_t count_bytes = (v->size - index - 1) * sizeof(void *); memmove(v->buffer + index, v->buffer + index + 1, count_bytes); } static void move_right(array_t *v, size_t index) { size_t count_bytes = (v->size - index) * sizeof(void *); memmove(v->buffer + index + 1, v->buffer + index, count_bytes); } static stat_t init_varg(array_t *v, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t ret = array_push_back(v, elem); if (ret != CDC_STATUS_OK) { return ret; } } return CDC_STATUS_OK; } stat_t array_ctor(array_t **v, data_info_t *info) { assert(v != NULL); array_t *tmp = (array_t *)calloc(sizeof(array_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } stat_t ret = CDC_STATUS_OK; if (info && !(tmp->dinfo = di_shared_ctorc(info))) { ret = CDC_STATUS_BAD_ALLOC; goto free_di; } ret = reallocate(tmp, ARRAY_MIN_CAPACITY); if (ret != CDC_STATUS_OK) { goto free_array; } *v = tmp; return ret; free_di: di_shared_dtor(tmp->dinfo); free_array: free(tmp); return ret; } stat_t array_ctorl(array_t **v, data_info_t *info, ...) { assert(v != NULL); va_list args; va_start(args, info); stat_t ret = array_ctorv(v, info, args); va_end(args); return ret; } stat_t array_ctorv(array_t **v, data_info_t *info, va_list args) { assert(v != NULL); stat_t ret = array_ctor(v, info); if (ret != CDC_STATUS_OK) { return ret; } return init_varg(*v, args); } void array_dtor(array_t *v) { assert(v != NULL); free_buffer(v); di_shared_dtor(v->dinfo); free(v); } stat_t array_insert(array_t *v, size_t index, void *value) { assert(v != NULL); assert(index <= v->size); if (should_grow(v)) { stat_t ret = grow(v); if (ret != CDC_STATUS_OK) { return ret; } } move_right(v, index); v->buffer[index] = value; ++v->size; return CDC_STATUS_OK; } void array_clear(array_t *v) { assert(v != NULL); free_data(v); v->size = 0; } void array_erase(array_t *v, size_t index) { assert(v != NULL); assert(index < v->size); if (CDC_HAS_DFREE(v->dinfo)) { v->dinfo->dfree(v->buffer[index]); } move_left(v, index); --v->size; } stat_t array_reserve(array_t *v, size_t capacity) { assert(v != NULL); if (capacity > v->capacity) { return reallocate(v, capacity); } return CDC_STATUS_OK; } stat_t array_shrink_to_fit(array_t *v) { assert(v != NULL); return reallocate(v, v->size); } stat_t array_push_back(array_t *v, void *value) { assert(v != NULL); return array_insert(v, v->size, value); } void array_swap(array_t *a, array_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(size_t, a->capacity, b->capacity); CDC_SWAP(void **, a->buffer, b->buffer); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } stat_t array_at(array_t *v, size_t index, void **elem) { assert(v != NULL); assert(elem != NULL); if (index > v->size) { return CDC_STATUS_OUT_OF_RANGE; } *elem = v->buffer[index]; return CDC_STATUS_OK; } stat_t array_append(array_t *v, void **data, size_t len) { assert(v != NULL); size_t new_capacity = v->size + len; if (new_capacity > v->capacity) { stat_t ret = reallocate(v, (size_t)(new_capacity * ARRAY_COPACITY_EXP)); if (ret != CDC_STATUS_OK) { return ret; } } memcpy(v->buffer + v->size, data, len * sizeof(void *)); v->size += len; return CDC_STATUS_OK; } stat_t array_append_move(array_t *v, array_t *other) { assert(v != NULL); assert(other != NULL); stat_t stat = array_append(v, other->buffer, other->size); if (stat != CDC_STATUS_OK) { return stat; } other->size = 0; return CDC_STATUS_OK; }
maksimandrianov/cdstructures
src/treap.c
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/treap.h" #include "cdcontainers/data-info.h" #include "cdcontainers/global.h" #include "cdcontainers/tree-utils.h" #include <stdint.h> #include <stdlib.h> #include <string.h> struct node_pair { treap_node_t *left; treap_node_t *right; }; CDC_MAKE_FIND_NODE_FN(treap_node_t *) CDC_MAKE_MIN_NODE_FN(treap_node_t *) CDC_MAKE_MAX_NODE_FN(treap_node_t *) CDC_MAKE_SUCCESSOR_FN(treap_node_t *) CDC_MAKE_PREDECESSOR_FN(treap_node_t *) static int default_prior(void *value) { CDC_UNUSED(value); return rand(); } static treap_node_t *make_new_node(void *key, int prior, void *val) { treap_node_t *node = (treap_node_t *)malloc(sizeof(treap_node_t)); if (!node) return NULL; node->priority = prior; node->key = key; node->value = val; node->parent = NULL; node->left = NULL; node->right = NULL; return node; } static void free_node(treap_t *t, treap_node_t *node) { if (CDC_HAS_DFREE(t->dinfo)) { pair_t pair = {node->key, node->value}; t->dinfo->dfree(&pair); } free(node); } static void free_treap(treap_t *t, treap_node_t *root) { if (root == NULL) { return; } free_treap(t, root->left); free_treap(t, root->right); free_node(t, root); } static struct node_pair split(treap_node_t *root, void *key, cdc_binary_pred_fn_t compar) { struct node_pair pair; if (root == NULL) { pair.left = NULL; pair.right = NULL; return pair; } if (compar(root->key, key)) { pair = split(root->right, key, compar); root->right = pair.left; if (pair.left) { pair.left->parent = root; } if (pair.right) { pair.right->parent = NULL; } pair.left = root; pair.right = pair.right; return pair; } else { pair = split(root->left, key, compar); root->left = pair.right; if (pair.left) { pair.left->parent = NULL; } if (pair.right) { pair.right->parent = root; } pair.left = pair.left; pair.right = root; return pair; } } static treap_node_t *merge(treap_node_t *l, treap_node_t *r) { if (l == NULL) { return r; } if (r == NULL) { return l; } if (l->priority > r->priority) { l->right = merge(l->right, r); if (l->right) { l->right->parent = l; } return l; } else { r->left = merge(l, r->left); if (r->left) { r->left->parent = r; } return r; } } static treap_node_t *find_nearest(treap_t *t, void *key, int priority) { treap_node_t *node = t->root; while (node) { if (node->priority <= priority) { break; } if (t->dinfo->cmp(key, node->key)) { if (node->left) { node = node->left; } else { break; } } else { if (node->right) { node = node->right; } else { break; } } } return node; } static void erase_node(treap_t *t, treap_node_t *node) { treap_node_t *tmp = merge(node->left, node->right); if (t->root == node) { if (tmp) { tmp->parent = NULL; } t->root = tmp; } else { if (tmp) { tmp->parent = node->parent; } if (node->parent->left && node->parent->left == node) { node->parent->left = tmp; } else { node->parent->right = tmp; } } --t->size; free_node(t, node); } static treap_node_t *insert_unique(treap_t *t, treap_node_t *node, treap_node_t *nearest) { if (t->root) { if (nearest->priority > node->priority) { if (t->dinfo->cmp(node->key, nearest->key)) { nearest->left = node; } else { nearest->right = node; } node->parent = nearest; } else { treap_node_t *pnode = nearest->parent; struct node_pair pair = split(nearest, node->key, t->dinfo->cmp); node->left = pair.left; if (pair.left) { pair.left->parent = node; } node->right = pair.right; if (pair.right) { pair.right->parent = node; } if (pnode == NULL) { node->parent = NULL; t->root = node; } else if (pnode->left == nearest) { node->parent = pnode; pnode->left = node; } else { node->parent = pnode; pnode->right = node; } } } else { t->root = node; } ++t->size; return node; } static stat_t init_varg(treap_t *t, va_list args) { pair_t *pair = NULL; while ((pair = va_arg(args, pair_t *)) != CDC_END) { stat_t stat = treap_insert(t, pair->first, pair->second, NULL); if (stat != CDC_STATUS_OK) { return stat; } } return CDC_STATUS_OK; } stat_t treap_ctor1(treap_t **t, data_info_t *info, cdc_priority_fn_t prior) { assert(t != NULL); assert(CDC_HAS_CMP(info)); treap_t *tmp = (treap_t *)calloc(sizeof(treap_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } tmp->prior = prior ? prior : default_prior; *t = tmp; return CDC_STATUS_OK; } stat_t treap_ctorl1(treap_t **t, data_info_t *info, cdc_priority_fn_t prior, ...) { assert(t != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, prior); stat_t stat = treap_ctorv1(t, info, prior, args); va_end(args); return stat; } stat_t treap_ctorv1(treap_t **t, data_info_t *info, cdc_priority_fn_t prior, va_list args) { assert(t != NULL); assert(CDC_HAS_CMP(info)); stat_t stat = treap_ctor1(t, info, prior); if (stat != CDC_STATUS_OK) { return stat; } return init_varg(*t, args); } stat_t treap_ctor(treap_t **t, data_info_t *info) { assert(t != NULL); assert(CDC_HAS_CMP(info)); return treap_ctor1(t, info, NULL); } stat_t treap_ctorl(treap_t **t, data_info_t *info, ...) { assert(t != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t stat = treap_ctorv(t, info, args); va_end(args); return stat; } stat_t treap_ctorv(treap_t **t, data_info_t *info, va_list args) { assert(t != NULL); assert(CDC_HAS_CMP(info)); return treap_ctorv1(t, info, NULL, args); } void treap_dtor(treap_t *t) { assert(t != NULL); free_treap(t, t->root); di_shared_dtor(t->dinfo); free(t); } stat_t treap_get(treap_t *t, void *key, void **value) { assert(t != NULL); treap_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (node) { *value = node->value; return CDC_STATUS_OK; } return CDC_STATUS_NOT_FOUND; } size_t treap_count(treap_t *t, void *key) { assert(t != NULL); return (size_t)(cdc_find_tree_node(t->root, key, t->dinfo->cmp) != NULL); } void treap_find(treap_t *t, void *key, treap_iter_t *it) { assert(t != NULL); assert(it != NULL); treap_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (!node) { treap_end(t, it); return; } it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } stat_t treap_insert(treap_t *t, void *key, void *value, pair_treap_iter_bool_t *ret) { assert(t != NULL); treap_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return treap_insert1(t, key, value, it, inserted); } stat_t treap_insert1(treap_t *t, void *key, void *value, treap_iter_t *it, bool *inserted) { assert(t != NULL); treap_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); bool finded = node; if (!node) { node = make_new_node(key, t->prior(value), value); if (!node) { return CDC_STATUS_BAD_ALLOC; } treap_node_t *nearest = find_nearest(t, node->key, node->priority); node = insert_unique(t, node, nearest); } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } stat_t treap_insert_or_assign(treap_t *t, void *key, void *value, pair_treap_iter_bool_t *ret) { assert(t != NULL); treap_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return treap_insert_or_assign1(t, key, value, it, inserted); } stat_t treap_insert_or_assign1(treap_t *t, void *key, void *value, treap_iter_t *it, bool *inserted) { assert(t != NULL); treap_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); bool finded = node; if (!node) { node = make_new_node(key, t->prior(value), value); if (!node) { return CDC_STATUS_BAD_ALLOC; } treap_node_t *nearest = find_nearest(t, node->key, node->priority); node = insert_unique(t, node, nearest); } else { node->value = value; } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } size_t treap_erase(treap_t *t, void *key) { assert(t != NULL); treap_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (node == NULL) { return 0; } erase_node(t, node); return 1; } void treap_clear(treap_t *t) { assert(t != NULL); free_treap(t, t->root); t->size = 0; t->root = NULL; } void treap_swap(treap_t *a, treap_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(treap_node_t *, a->root, b->root); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(cdc_priority_fn_t, a->prior, b->prior); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void treap_begin(treap_t *t, treap_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = cdc_min_tree_node(t->root); it->prev = NULL; } void treap_end(treap_t *t, treap_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = NULL; it->prev = cdc_max_tree_node(t->root); } void treap_iter_next(treap_iter_t *it) { assert(it != NULL); it->prev = it->current; it->current = cdc_tree_successor(it->current); } void treap_iter_prev(treap_iter_t *it) { assert(it != NULL); it->current = it->prev; it->prev = cdc_tree_predecessor(it->current); }
maksimandrianov/cdstructures
include/cdcontainers/treap.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_treap is a struct and functions that provide a cartesion tree. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_TREAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_TREAP_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> /** * @defgroup cdc_treap * @brief The cdc_treap is a struct and functions that provide a treap. * @{ */ typedef int (*cdc_priority_fn_t)(void *); /** * @brief The cdc_treap_node is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_treap_node { struct cdc_treap_node *parent; struct cdc_treap_node *left; struct cdc_treap_node *right; void *key; void *value; int priority; }; /** * @brief The cdc_treap is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_treap { struct cdc_treap_node *root; size_t size; cdc_priority_fn_t prior; struct cdc_data_info *dinfo; }; /** * @brief The cdc_treap_iter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_treap_iter { struct cdc_treap *container; struct cdc_treap_node *prev; struct cdc_treap_node *current; }; struct cdc_pair_treap_iter_bool { struct cdc_treap_iter first; bool second; }; // Base /** * @defgroup cdc_treap_base Base * @{ */ /** * @brief Constructs an empty treap. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_ctor(struct cdc_treap **t, struct cdc_data_info *info); /** * @brief Constructs a treap, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_treap *tree = NULL; * cdc_pair value1 = {CDC_FROM_INT(1), CDC_FROM_INT(2)}; * cdc_pair value2 = {CDC_FROM_INT(3), CDC_FROM_INT(4)}; * ... * if (cdc_treap_ctorl(&tree, info, &value1, &value2, CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_treap_ctorl(struct cdc_treap **t, struct cdc_data_info *info, ...); /** * @brief Constructs a treap, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_ctorv(struct cdc_treap **t, struct cdc_data_info *info, va_list args); /** * @brief Constructs an empty treap. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @param[in] prior - function that generates a priority * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_ctor1(struct cdc_treap **t, struct cdc_data_info *info, cdc_priority_fn_t prior); /** * @brief Constructs a treap, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @param[in] prior - function that generates a priority * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_ctorl1(struct cdc_treap **t, struct cdc_data_info *info, cdc_priority_fn_t prior, ...); /** * @brief Constructs a treap, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_treap * @param[in] info - cdc_data_info * @param[in] prior - function that generates a priority * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_ctorv1(struct cdc_treap **t, struct cdc_data_info *info, cdc_priority_fn_t prior, va_list args); /** * @brief Destroys the treap. * @param[in] t - cdc_treap */ void cdc_treap_dtor(struct cdc_treap *t); /** @} */ // Lookup /** * @defgroup cdc_treap_lookup Lookup * @{ */ /** * @brief Returns a value that is mapped to a key. If the key does * not exist, then NULL will return. * @param[in] t - cdc_treap * @param[in] key - key of the element to find * @param[out] value - pinter to the value that is mapped to a key. * @return CDC_STATUS_OK if the key is found, CDC_STATUS_NOT_FOUND otherwise. */ enum cdc_stat cdc_treap_get(struct cdc_treap *t, void *key, void **value); /** * @brief Returns the number of elements with key that compares equal to the * specified argument key, which is either 1 or 0 since this container does not * allow duplicates. * @param[in] t - cdc_treap * @param[in] key - key value of the elements to count * @return number of elements with key key, that is either 1 or 0. */ size_t cdc_treap_count(struct cdc_treap *t, void *key); /** * @brief Finds an element with key equivalent to key. * @param[in] t - cdc_treap * @param[in] key - key value of the element to search for * @param[out] it - pointer will be recorded iterator to an element with key * equivalent to key. If no such element is found, past-the-end iterator is * returned. */ void cdc_treap_find(struct cdc_treap *t, void *key, struct cdc_treap_iter *it); /** @} */ // Capacity /** * @defgroup cdc_treap_capacity Capacity * @{ */ /** * @brief Returns the number of items in the treap. * @param[in] t - cdc_treap * @return the number of items in the treap. */ static inline size_t cdc_treap_size(struct cdc_treap *t) { assert(t != NULL); return t->size; } /** * @brief Checks if the treap has no elements. * @param[in] t - cdc_treap * @return true if the treap is empty, false otherwise. */ static inline bool cdc_treap_empty(struct cdc_treap *t) { assert(t != NULL); return t->size == 0; } /** @} */ // Modifiers /** * @defgroup cdc_treap_modifiers Modifiers * @{ */ /** * @brief Removes all the elements from the treap. * @param[in] t - cdc_treap */ void cdc_treap_clear(struct cdc_treap *t); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_treap * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair consisting of an iterator to the inserted element (or to * the element that prevented the insertion) and a bool denoting whether the * insertion took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_insert(struct cdc_treap *t, void *key, void *value, struct cdc_pair_treap_iter_bool *ret); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_treap * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator to the inserted element (or to the element that * prevented the insertion). The pointer can be equal to NULL. * @param[out] inserted - bool denoting whether the insertion * took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_insert1(struct cdc_treap *t, void *key, void *value, struct cdc_treap_iter *it, bool *inserted); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_treap * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair. The bool component is true if the insertion took place and * false if the assignment took place. The iterator component is pointing at the * element that was inserted or updated. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_insert_or_assign(struct cdc_treap *t, void *key, void *value, struct cdc_pair_treap_iter_bool *ret); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_treap * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator is pointing at the element that was inserted or updated. * The pointer can be equal to NULL * @param[out] inserted - bool is true if the insertion took place and false if the * assignment took place. The pointer can be equal to NULL * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_treap_insert_or_assign1(struct cdc_treap *t, void *key, void *value, struct cdc_treap_iter *it, bool *inserted); /** * @brief Removes the element (if one exists) with the key equivalent to key. * @param[in] t - cdc_treap * @param[in] key - key value of the elements to remove * @return number of elements removed. */ size_t cdc_treap_erase(struct cdc_treap *t, void *key); /** * @brief Swaps treaps a and b. This operation is very fast and never fails. * @param[in, out] a - cdc_treap * @param[in, out] b - cdc_treap */ void cdc_treap_swap(struct cdc_treap *a, struct cdc_treap *b); /** @} */ // Iterators /** * @defgroup cdc_treap_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param t[in] - cdc_treap * @param it[out] - cdc_treap_iter */ void cdc_treap_begin(struct cdc_treap *t, struct cdc_treap_iter *it); /** * @brief Initializes the iterator to the end. * @param[in] t - cdc_treap * @param[out] it - cdc_treap_iter */ void cdc_treap_end(struct cdc_treap *t, struct cdc_treap_iter *it); /** @} */ // Iterators /** * @defgroup cdc_treap_iter * @brief The cdc_treap_iter is a struct and functions that provide a treap iterator. * @{ */ /** * @brief Advances the iterator to the next element in the treap. * @param[in] it - iterator */ void cdc_treap_iter_next(struct cdc_treap_iter *it); /** * @brief Advances the iterator to the previous element in the treap. * @param[in] it - iterator */ void cdc_treap_iter_prev(struct cdc_treap_iter *it); /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_treap_iter_has_next(struct cdc_treap_iter *it) { assert(it != NULL); return it->current != NULL; } /** * @brief Returns true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. */ static inline bool cdc_treap_iter_has_prev(struct cdc_treap_iter *it) { assert(it != NULL); return it->prev != NULL; } /** * @brief Returns an item's key. * @param[in] it - iterator * @return the item's key. */ static inline void *cdc_treap_iter_key(struct cdc_treap_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns an item's value. * @param[in] it - iterator * @return the item's value. */ static inline void *cdc_treap_iter_value(struct cdc_treap_iter *it) { assert(it != NULL); return it->current->value; } /** * @brief Returns a pair, where first - key, second - value. * @param[in] it - iterator * @return pair, where first - key, second - value. */ static inline struct cdc_pair cdc_treap_iter_key_value(struct cdc_treap_iter *it) { assert(it != NULL); struct cdc_pair pair = {it->prev->key, it->prev->value}; return pair; } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_treap_iter_is_eq(struct cdc_treap_iter *it1, struct cdc_treap_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->prev == it2->prev && it1->current == it2->current; } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_treap_node treap_node_t; typedef struct cdc_treap treap_t; typedef struct cdc_treap_iter treap_iter_t; typedef struct cdc_pair_treap_iter pair_treap_iter_t; typedef struct cdc_pair_treap_iter_bool pair_treap_iter_bool_t; // Base #define treap_ctor(...) cdc_treap_ctor(__VA_ARGS__) #define treap_ctorv(...) cdc_treap_ctorv(__VA_ARGS__) #define treap_ctorl(...) cdc_treap_ctorl(__VA_ARGS__) #define treap_ctor1(...) cdc_treap_ctor1(__VA_ARGS__) #define treap_ctorv1(...) cdc_treap_ctorv1(__VA_ARGS__) #define treap_ctorl1(...) cdc_treap_ctorl1(__VA_ARGS__) #define treap_dtor(...) cdc_treap_dtor(__VA_ARGS__) // Lookup #define treap_get(...) cdc_treap_get(__VA_ARGS__) #define treap_count(...) cdc_treap_count(__VA_ARGS__) #define treap_find(...) cdc_treap_find(__VA_ARGS__) // Capacity #define treap_size(...) cdc_treap_size(__VA_ARGS__) #define treap_empty(...) cdc_treap_empty(__VA_ARGS__) // Modifiers #define treap_clear(...) cdc_treap_clear(__VA_ARGS__) #define treap_insert(...) cdc_treap_insert(__VA_ARGS__) #define treap_insert1(...) cdc_treap_insert1(__VA_ARGS__) #define treap_insert_or_assign(...) cdc_treap_insert_or_assign(__VA_ARGS__) #define treap_insert_or_assign1(...) cdc_treap_insert_or_assign1(__VA_ARGS__) #define treap_erase(...) cdc_treap_erase(__VA_ARGS__) #define treap_swap(...) cdc_treap_swap(__VA_ARGS__) // Iterators #define treap_begin(...) cdc_treap_begin(__VA_ARGS__) #define treap_end(...) cdc_treap_end(__VA_ARGS__) // Iterators #define treap_iter_next(...) cdc_treap_iter_next(__VA_ARGS__) #define treap_iter_prev(...) cdc_treap_iter_prev(__VA_ARGS__) #define treap_iter_has_next(...) cdc_treap_iter_has_next(__VA_ARGS__) #define treap_iter_has_prev(...) cdc_treap_iter_has_prev(__VA_ARGS__) #define treap_iter_key(...) cdc_treap_iter_key(__VA_ARGS__) #define treap_iter_value(...) cdc_treap_iter_value(__VA_ARGS__) #define treap_iter_key_value(...) cdc_treap_iter_key_value(__VA_ARGS__) #define treap_iter_is_eq(...) cdc_treap_iter_is_eq(__VA_ARGS__) #endif /** @} */ #endif // CDSTRUCTURES_INCLUDE_CDCONTAINERS_VECTOR_H
maksimandrianov/cdstructures
src/binomial-heap.c
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/binomial-heap.h" #include "cdcontainers/data-info.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> static binomial_heap_node_t *new_node(void *key) { binomial_heap_node_t *node = (binomial_heap_node_t *)calloc(sizeof(binomial_heap_node_t), 1); if (!node) return NULL; node->key = key; return node; } static void free_node(binomial_heap_t *h, binomial_heap_node_t *node) { if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(node->key); } free(node); } static void free_heap(binomial_heap_t *h, binomial_heap_node_t *root) { binomial_heap_node_t *tmp = NULL; while (root) { free_heap(h, root->child); tmp = root->sibling; free_node(h, root); root = tmp; } } static bool is_heap(binomial_heap_node_t *root, cdc_binary_pred_fn_t compar) { while (root) { if (!is_heap(root->child, compar) || (root->parent && compar(root->key, root->parent->key))) { return false; } root = root->sibling; } return true; } static binomial_heap_node_t *find_prev_top(binomial_heap_t *h) { if (h->root == NULL) { return NULL; } binomial_heap_node_t *m = h->root; binomial_heap_node_t *prev = NULL; binomial_heap_node_t *next = h->root; while (next->sibling) { prev = next; if (h->dinfo->cmp(m->key, next->key)) { m = next->key; } next = next->sibling; } return prev; } static binomial_heap_node_t *find_top(binomial_heap_t *h) { binomial_heap_node_t *node = find_prev_top(h); return node ? node->sibling : h->root; } static void update_top(binomial_heap_t *h, binomial_heap_node_t *v) { if (h->top == NULL || (v && h->dinfo->cmp(v->key, h->top->key))) { h->top = v; } } static void link(binomial_heap_node_t *a, binomial_heap_node_t *broot) { a->parent = broot; a->sibling = broot->child; broot->child = a; ++broot->degree; } static binomial_heap_node_t *merge(binomial_heap_node_t *a, binomial_heap_node_t *b) { if (a == NULL) { return b; } if (b == NULL) { return a; } binomial_heap_node_t *result = NULL; binomial_heap_node_t *next = NULL; while (b != NULL && a != NULL) { if (a->degree < b->degree) { if (result == NULL) { result = next = a; } else { next->sibling = a; next = a; } a = a->sibling; } else { if (result == NULL) { result = next = b; } else { next->sibling = b; next = b; } b = b->sibling; } } if (a == NULL) { next->sibling = b; } else { next->sibling = a; } return result; } static binomial_heap_node_t *meld(binomial_heap_node_t *a, binomial_heap_node_t *b, cdc_binary_pred_fn_t compare) { binomial_heap_node_t *result = merge(a, b); if (result == NULL) { return result; } binomial_heap_node_t *prev = NULL; binomial_heap_node_t *curr = result; binomial_heap_node_t *next = result->sibling; while (next) { if (curr->degree != next->degree || (next->sibling && (next->sibling->degree == curr->degree))) { prev = curr; curr = next; } else if (compare(curr->key, next->key)) { curr->sibling = next->sibling; link(next, curr); } else { if (prev == NULL) { result = next; } else { prev->sibling = next; } link(curr, next); next = curr; } next = curr->sibling; } return result; } static binomial_heap_node_t *decrease_key(binomial_heap_t *h, binomial_heap_node_t *node, void *key) { if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(node->key); } node->key = key; binomial_heap_node_t *p = node->parent; while (p != NULL && h->dinfo->cmp(node->key, p->key)) { CDC_SWAP(void *, node->key, p->key); node = p; p = node->parent; } return node; } static binomial_heap_node_t *increase_key(binomial_heap_t *h, binomial_heap_node_t *pos, void *key) { if (CDC_HAS_DFREE(h->dinfo)) { h->dinfo->dfree(pos->key); } pos->key = key; binomial_heap_node_t *ch = pos->child, *t = NULL; while (ch != NULL) { if (h->dinfo->cmp(ch->key, pos->key)) { t = ch; while (ch->sibling != NULL) { if (h->dinfo->cmp(ch->sibling->key, t->key)) { t = ch->sibling; } ch = ch->sibling; } CDC_SWAP(void *, t->key, pos->key); pos = t; ch = pos->child; } else { ch = ch->sibling; } } return pos; } static stat_t init_varg(binomial_heap_t *h, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t ret = binomial_heap_insert(h, elem); if (ret != CDC_STATUS_OK) { return ret; } } return CDC_STATUS_OK; } stat_t binomial_heap_ctor(binomial_heap_t **h, data_info_t *info) { assert(h != NULL); assert(CDC_HAS_CMP(info)); binomial_heap_t *tmp = (binomial_heap_t *)calloc(sizeof(binomial_heap_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } *h = tmp; return CDC_STATUS_OK; } stat_t binomial_heap_ctorl(binomial_heap_t **h, data_info_t *info, ...) { assert(h != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t ret = binomial_heap_ctorv(h, info, args); va_end(args); return ret; } stat_t binomial_heap_ctorv(binomial_heap_t **h, data_info_t *info, va_list args) { assert(h != NULL); assert(CDC_HAS_CMP(info)); stat_t ret = binomial_heap_ctor(h, info); if (ret != CDC_STATUS_OK) { return ret; } return init_varg(*h, args); } void binomial_heap_dtor(binomial_heap_t *h) { assert(h != NULL); free_heap(h, h->root); di_shared_dtor(h->dinfo); free(h); } stat_t binomial_heap_extract_top(binomial_heap_t *h) { assert(h != NULL); binomial_heap_node_t *tmp = NULL; binomial_heap_node_t *prev_top = find_prev_top(h); if (prev_top) { tmp = prev_top->sibling; prev_top->sibling = tmp->sibling; } else { tmp = h->root; h->root = tmp->sibling; } binomial_heap_node_t *root = tmp->child; free_node(h, tmp); tmp = root; while (tmp) { tmp->parent = NULL; tmp = tmp->sibling; } h->root = meld(h->root, root, h->dinfo->cmp); h->top = find_top(h); --h->size; return CDC_STATUS_OK; } stat_t binomial_heap_riinsert(binomial_heap_t *h, void *key, binomial_heap_iter_t *ret) { assert(h != NULL); binomial_heap_node_t *node = new_node(key); if (!node) return CDC_STATUS_BAD_ALLOC; update_top(h, node); h->root = meld(h->root, node, h->dinfo->cmp); ++h->size; if (ret) { ret->container = h; ret->current = node; } return CDC_STATUS_OK; } void binomial_heap_change_key(binomial_heap_t *h, binomial_heap_iter_t *pos, void *key) { assert(h != NULL); assert(pos != NULL); assert(h == pos->container); binomial_heap_node_t *node = NULL; binomial_heap_node_t *curr = pos->current; if (h->dinfo->cmp(key, curr->key)) { node = decrease_key(h, curr, key); update_top(h, node); } else { node = increase_key(h, curr, key); if (curr == h->top) { h->top = find_top(h); } } pos->current = node; } void binomial_heap_clear(binomial_heap_t *h) { assert(h != NULL); free_heap(h, h->root); h->size = 0; h->root = NULL; h->top = NULL; } void binomial_heap_swap(binomial_heap_t *a, binomial_heap_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(binomial_heap_node_t *, a->root, b->root); CDC_SWAP(binomial_heap_node_t *, a->top, b->top); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void binomial_heap_merge(binomial_heap_t *h, binomial_heap_t *other) { assert(h != NULL); assert(other != NULL); h->root = meld(h->root, other->root, h->dinfo->cmp); update_top(h, other->top); h->size += other->size; other->size = 0; other->root = NULL; other->top = NULL; } bool binomial_heap_is_heap(binomial_heap_t *h) { assert(h != NULL); return is_heap(h->root, h->dinfo->cmp); }
maksimandrianov/cdstructures
examples/array.c
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // Program to find first n prime numbers. #define CDC_USE_SHORT_NAMES #include <cdcontainers/cdc.h> #include <stdio.h> // This function based on the Sieve of Eratosthenes. // https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes array_t *find_uint_prime_numbers(unsigned int n) { array_t *numbers = NULL; if (array_ctor(&numbers, NULL /* data info */) != CDC_STATUS_OK) { return NULL; } array_reserve(numbers, n + 1); for (unsigned int i = 0; i < n + 1; ++i) { array_push_back(numbers, CDC_FROM_UINT(i)); } array_t *prime_numbers = NULL; if (array_ctor(&prime_numbers, NULL /* data info */) != CDC_STATUS_OK) { array_dtor(numbers); return NULL; } for (unsigned int p = 2; p < n + 1; ++p) { void *val = array_get(numbers, p); if (CDC_TO_UINT(val) != 0) { if (array_push_back(prime_numbers, val) != CDC_STATUS_OK) { array_dtor(prime_numbers); array_dtor(numbers); return NULL; } for (unsigned int i = p * p; i < n + 1; i += p) { array_set(numbers, i, CDC_FROM_UINT(0)); } } } array_dtor(numbers); return prime_numbers; } int main(int argc, char **argv) { CDC_UNUSED(argc); CDC_UNUSED(argv); array_t *prime_numbers = find_uint_prime_numbers(1000); if (!prime_numbers) { return EXIT_FAILURE; } for (unsigned i = 0; i < array_size(prime_numbers); ++i) { printf("%u ", CDC_TO_UINT(array_get(prime_numbers, i))); } printf("\n"); array_dtor(prime_numbers); return EXIT_SUCCESS; }
maksimandrianov/cdstructures
src/tables/seq-array.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/array.h" #include "cdcontainers/tables/isequence.h" #include <assert.h> static stat_t ctor(void **cntr, data_info_t *info) { assert(cntr != NULL); array_t **array = (array_t **)cntr; return array_ctor(array, info); } static stat_t ctorv(void **cntr, data_info_t *info, va_list args) { assert(cntr != NULL); array_t **array = (array_t **)cntr; return array_ctorv(array, info, args); } static void dtor(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_dtor(array); } static void *front(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_front(array); } static void *back(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_back(array); } static bool empty(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_empty(array); } static size_t size(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_size(array); } static stat_t push_back(void *cntr, void *elem) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_push_back(array, elem); } static void pop_back(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_pop_back(array); } static stat_t push_front(void *cntr, void *elem) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_insert(array, 0, elem); } static void pop_front(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_erase(array, 0); } static stat_t insert(void *cntr, size_t index, void *value) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_insert(array, index, value); } static void erase(void *cntr, size_t index) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_erase(array, index); } static void clear(void *cntr) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_clear(array); } static void *get(void *cntr, size_t index) { assert(cntr != NULL); array_t *array = (array_t *)cntr; return array_get(array, index); } static void set(void *cntr, size_t index, void *value) { assert(cntr != NULL); array_t *array = (array_t *)cntr; array_set(array, index, value); } static const sequence_table_t _table = {.ctor = ctor, .ctorv = ctorv, .dtor = dtor, .front = front, .back = back, .empty = empty, .size = size, .push_back = push_back, .pop_back = pop_back, .push_front = push_front, .pop_front = pop_front, .insert = insert, .erase = erase, .clear = clear, .get = get, .set = set}; const sequence_table_t *cdc_seq_array = &_table;
maksimandrianov/cdstructures
include/cdcontainers/array.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file array.h * @brief The cdc_array is a struct and functions that provide a dynamic array. * * Example usage array: * @include array.c * * @author <NAME> <<EMAIL>> */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_VECTOR_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_VECTOR_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> /** * @defgroup cdc_array * @brief The cdc_array is a struct and functions that provide a dynamic array. * @{ */ /** * @brief The cdc_array is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_array { size_t size; size_t capacity; void **buffer; struct cdc_data_info *dinfo; }; // Base /** * @defgroup cdc_array_base Base * @{ */ /** * @brief Constructs an empty array. * @param[out] v - cdc_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_ctor(struct cdc_array **v, struct cdc_data_info *info); /** * @brief Constructs an array, initialized by an variable number of pointers. * The last pointer must be CDC_END. * @param[out] v - cdc_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_array *vec = NULL; * if (cdc_array_ctorl(&vec, NULL, CDC_FROM_INT(1), * CDC_FROM_INT(2), CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_array_ctorl(struct cdc_array **v, struct cdc_data_info *info, ...); /** * @brief Constructs an array, initialized by args. The last pointer must be CDC_END. * @param[out] v - cdc_array * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_ctorv(struct cdc_array **v, struct cdc_data_info *info, va_list args); /** * @brief Destroys the array. * @param[in] v - cdc_array */ void cdc_array_dtor(struct cdc_array *v); /** @} */ // Element access /** * @defgroup cdc_array_element_access Element access * @{ */ /** * @brief Returns an element at index position in the array * @param[in] v - cdc_array * @param[in] index - index of an element to return * @return element from |index| position. */ static inline void *cdc_array_get(struct cdc_array *v, size_t index) { assert(v != NULL); assert(index < v->size); return v->buffer[index]; } /** * @brief Writes to pointer an element from specified position in the array. * Bounds checking is performed. * @param[in] v - cdc_array * @param[in] index - index of an element to write at elem * @param[out] elem - pointer where an element will be written * @return DC_STATUS_OK in a successful case or CDC_STATUS_OUT_OF_RANGE if the * index is incorrect. */ enum cdc_stat cdc_array_at(struct cdc_array *v, size_t index, void **elem); /** * @brief Returns a first element in the array. * @param[in] v - cdc_array * @return first element in the array. */ static inline void *cdc_array_front(struct cdc_array *v) { assert(v != NULL); assert(v->size > 0); return v->buffer[0]; } /** * @brief Returns a last element in the array. * @param[in] v - cdc_array * @return last element in the array. */ static inline void *cdc_array_back(struct cdc_array *v) { assert(v != NULL); assert(v->size > 0); return v->buffer[v->size - 1]; } /** * @brief Returns a pointer to the data stored in the array. * @param[in] v - cdc_array * @return pointer to the data stored in the array. */ static inline void **cdc_array_data(struct cdc_array *v) { assert(v != NULL); return v->buffer; } /** @} */ // Capacity /** * @defgroup cdc_array_capacity Capacity * @{ */ /** * @brief Attempts to allocate memory for at least size elements. * If you know in advance how large the array will be, you should call this * function to prevent reallocations and memory fragmentation. * @param[in] v - cdc_array * @param[in] capacity - new capacity * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_reserve(struct cdc_array *v, size_t capacity); /** * @brief Checks if the array has no elements. * @param[in] v - cdc_array * @return true if the array is empty, false otherwise. */ static inline bool cdc_array_empty(struct cdc_array *v) { assert(v != NULL); return v->size == 0; } /** * @brief Returns the number of elements in the array. * @param[in] v - cdc_array * @return the number of elements in the array. */ static inline size_t cdc_array_size(struct cdc_array *v) { assert(v != NULL); return v->size; } /** * @brief Returns the number of elements that the container has currently allocated space for. * @param[in] v - cdc_array * @return capacity of the currently allocated storage. */ static inline size_t cdc_array_capacity(struct cdc_array *v) { assert(v != NULL); return v->capacity; } /** * @brief Requests the container to reduce its capacity to fit its size. * @param[in] v - cdc_array * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_array_shrink_to_fit(struct cdc_array *v); /** @} */ // Modifiers /** * @defgroup cdc_array_modifiers Modifiers * @{ */ /** * @brief Sets an element at index position to the value. The function is not * called to free memory. * @param[in] v - cdc_array * @param[in] index - index position where the value will be written * @param[in] value - value */ static inline void cdc_array_set(struct cdc_array *v, size_t index, void *value) { assert(v != NULL); assert(index < v->size); v->buffer[index] = value; } /** * @brief Inserts value at |index| position in the array. If index is 0, the * value is prepended to the array. If index is cdc_array_size(), the value is * appended to the array. * @param[in] v - cdc_array * @param[in] index - index position where an element will be inserted * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_insert(struct cdc_array *v, size_t index, void *value); /** * @brief Removes an element at index position in the arrray. * @param[in] v - cdc_array * @param[in] index - index position where an element will be removed */ void cdc_array_erase(struct cdc_array *v, size_t index); /** * @brief Removes all the elements from the array. * @param[in] v - cdc_array */ void cdc_array_clear(struct cdc_array *v); /** * @brief Inserts an element at the end of the array. * @param[in] v - cdc_array * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_push_back(struct cdc_array *v, void *value); /** * @brief Removes a last element in the array. * @param[in] v - cdc_array */ static inline void cdc_array_pop_back(struct cdc_array *v) { assert(v != NULL); assert(v->size > 0); cdc_array_erase(v, v->size - 1); } /** * @brief Appends elements at the end of array. * @param[in] v - cdc_array * @param[in] data - pointer on data * @param[in] len - the number of data elements * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_append(struct cdc_array *v, void **data, size_t len); /** * @brief Appends one array to the end of other array. * @param[in] v - cdc_array * @param[in] other - cdc_array * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_array_append_move(struct cdc_array *v, struct cdc_array *other); /** * @brief Swaps arrays. This operation is very fast and never fails. * @param[in, out] a - cdc_array * @param[in, out] b - cdc_array */ void cdc_array_swap(struct cdc_array *a, struct cdc_array *b); /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_array array_t; // Base #define array_ctor(...) cdc_array_ctor(__VA_ARGS__) #define array_ctorl(...) cdc_array_ctorl(__VA_ARGS__) #define array_ctorv(...) cdc_array_ctorv(__VA_ARGS__) #define array_dtor(...) cdc_array_dtor(__VA_ARGS__) // Element access #define array_get(...) cdc_array_get(__VA_ARGS__) #define array_at(...) cdc_array_at(__VA_ARGS__) #define array_front(...) cdc_array_front(__VA_ARGS__) #define array_back(...) cdc_array_back(__VA_ARGS__) #define array_data(...) cdc_array_data(__VA_ARGS__) // Capacity #define array_reserve(...) cdc_array_reserve(__VA_ARGS__) #define array_empty(...) cdc_array_empty(__VA_ARGS__) #define array_size(...) cdc_array_size(__VA_ARGS__) #define array_capacity(...) cdc_array_capacity(__VA_ARGS__) #define array_cap_exp(...) cdc_array_cap_exp(__VA_ARGS__) #define array_shrink_to_fit(...) cdc_array_shrink_to_fit(__VA_ARGS__) // Modifiers #define array_set(...) cdc_array_set(__VA_ARGS__) #define array_insert(...) cdc_array_insert(__VA_ARGS__) #define array_erase(...) cdc_array_erase(__VA_ARGS__) #define array_clear(...) cdc_array_clear(__VA_ARGS__) #define array_push_back(...) cdc_array_push_back(__VA_ARGS__) #define array_pop_back(...) cdc_array_pop_back(__VA_ARGS__) #define array_append(...) cdc_array_append(__VA_ARGS__) #define array_append_move(...) cdc_array_append_move(__VA_ARGS__) #define array_swap(...) cdc_array_swap(__VA_ARGS__) #endif /** @} */ #endif // CDSTRUCTURES_INCLUDE_CDCONTAINERS_VECTOR_H
maksimandrianov/cdstructures
tests/test-common.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef CDCONTAINERS_TESTS_TESTS_COMMON_H #define CDCONTAINERS_TESTS_TESTS_COMMON_H #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> // Common tests void test_ptr_float_cast(); void test_ptr_double_cast(); // Array tests void test_array_ctor(); void test_array_ctorl(); void test_array_reserve(); void test_array_data(); void test_array_get(); void test_array_at(); void test_array_set(); void test_array_front(); void test_array_back(); void test_array_insert(); void test_array_erase(); void test_array_clear(); void test_array_push_back(); void test_array_pop_back(); void test_array_swap(); void test_array_shrink_to_fit(); // List tests void test_list_ctor(); void test_list_ctorl(); void test_list_push_back(); void test_list_push_front(); void test_list_at(); void test_list_front(); void test_list_back(); void test_list_pop_back(); void test_list_pop_front(); void test_list_swap(); void test_list_insert(); void test_list_erase(); void test_list_ierase(); void test_list_clear(); void test_list_iterators(); void test_list_reverse_iterators(); void test_list_splice(); void test_list_ssplice(); void test_list_lsplice(); void test_list_merge(); void test_list_erase_if(); void test_list_reverse(); void test_list_unique(); void test_list_sort(); // Stackv tests void test_stackv_ctor(); void test_stackv_ctorl(); void test_stackv_push(); void test_stackv_pop(); void test_stackv_swap(); // Queued tests void test_queued_ctor(); void test_queued_ctorl(); void test_queued_push(); void test_queued_pop(); void test_queued_front(); void test_queued_back(); void test_queued_swap(); // Circular array tests void test_circular_array_ctor(); void test_circular_array_ctorl(); void test_circular_array_push_back(); void test_circular_array_push_front(); void test_circular_array_get(); void test_circular_array_at(); void test_circular_array_set(); void test_circular_array_front(); void test_circular_array_back(); void test_circular_array_pop_back(); void test_circular_array_pop_front(); void test_circular_array_swap(); void test_circular_array_insert(); void test_circular_array_erase(); void test_circular_array_clear(); void test_circular_array_pop_push(); // Deque tests void test_deque_ctor(); void test_deque_ctorl(); void test_deque_push_back(); void test_deque_push_front(); void test_deque_get(); void test_deque_set(); void test_deque_front(); void test_deque_back(); void test_deque_pop_back(); void test_deque_pop_front(); void test_deque_swap(); void test_deque_insert(); void test_deque_erase(); void test_deque_clear(); void test_deque_pop_push(); // Heap tests void test_heap_ctor(); void test_heap_ctorl(); void test_heap_top(); void test_heap_extract_top(); void test_heap_insert(); void test_heap_change_key(); void test_heap_merge(); void test_heap_swap(); // Binomial heap tests void test_binomial_heap_ctor(); void test_binomial_heap_ctorl(); void test_binomial_heap_dtor(); void test_binomial_heap_top(); void test_binomial_heap_extract_top(); void test_binomial_heap_insert(); void test_binomial_heap_change_key(); void test_binomial_heap_merge(); void test_binomial_heap_swap(); // Pairing heap tests void test_pairing_heap_ctor(); void test_pairing_heap_ctorl(); void test_pairing_heap_dtor(); void test_pairing_heap_top(); void test_pairing_heap_extract_top(); void test_pairing_heap_insert(); void test_pairing_heap_change_key(); void test_pairing_heap_merge(); void test_pairing_heap_swap(); // Priority queue tests void test_priority_queue_ctor(); void test_priority_queue_ctorl(); void test_priority_queue_push(); void test_priority_queue_pop(); void test_priority_queue_top(); void test_priority_queue_swap(); // Treap tests void test_treap_ctor(); void test_treap_ctorl(); void test_treap_insert(); void test_treap_erase(); void test_treap_swap(); void test_treap_iterators(); void test_treap_get(); void test_treap_count(); void test_treap_find(); void test_treap_treap(); void test_treap_clear(); void test_treap_insert_or_assign(); void test_treap_erase(); void test_treap_height(); // Hash table tests void test_hash_table_ctor(); void test_hash_table_ctorl(); void test_hash_table_get(); void test_hash_table_count(); void test_hash_table_find(); void test_hash_table_clear(); void test_hash_table_insert(); void test_hash_table_insert_or_assign(); void test_hash_table_erase(); void test_hash_table_swap(); void test_hash_table_rehash(); void test_hash_table_reserve(); // Splay tree tests void test_splay_tree_ctor(); void test_splay_tree_ctorl(); void test_splay_tree_insert(); void test_splay_tree_erase(); void test_splay_tree_swap(); void test_splay_tree_iterators(); void test_splay_tree_get(); void test_splay_tree_count(); void test_splay_tree_find(); void test_splay_tree_clear(); void test_splay_tree_insert_or_assign(); void test_splay_tree_erase(); void test_splay_tree_height(); // Avl tree tests void test_avl_tree_ctor(); void test_avl_tree_ctorl(); void test_avl_tree_insert(); void test_avl_tree_erase(); void test_avl_tree_swap(); void test_avl_tree_iterators(); void test_avl_tree_get(); void test_avl_tree_count(); void test_avl_tree_find(); void test_avl_tree_clear(); void test_avl_tree_insert_or_assign(); void test_avl_tree_erase(); void test_avl_tree_height(); // Map tests void test_map_ctor(); void test_map_ctorl(); void test_map_insert(); void test_map_erase(); void test_map_swap(); void test_map_iterators(); void test_map_get(); void test_map_count(); void test_map_find(); void test_map_clear(); void test_map_insert_or_assign(); void test_map_erase(); void test_map_iter_type(); #endif // CDSTRUCTURES_TESTS_TESTS_COMMON_H
maksimandrianov/cdstructures
include/cdcontainers/tables/ipqueue.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_priority_queue_table is a priority queue interface */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IPQUEUE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IPQUEUE_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_priority_queue_table struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_priority_queue_table { enum cdc_stat (*ctor)(void **cntr, struct cdc_data_info *info); enum cdc_stat (*ctorv)(void **cntr, struct cdc_data_info *info, va_list args); void (*dtor)(void *cntr); void *(*top)(void *cntr); bool (*empty)(void *cntr); size_t (*size)(void *cntr); enum cdc_stat (*push)(void *cntr, void *elem); void (*pop)(void *cntr); }; extern const struct cdc_priority_queue_table *cdc_pq_heap; extern const struct cdc_priority_queue_table *cdc_pq_binheap; extern const struct cdc_priority_queue_table *cdc_pq_pheap; // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_priority_queue_table priority_queue_table_t; #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IPQUEUE_H
maksimandrianov/cdstructures
src/heap.c
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/heap.h" #include "cdcontainers/data-info.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> static size_t parent(size_t i) { return (i - 1) / 2; } static size_t left(size_t i) { return 2 * i + 1; } static size_t right(size_t i) { return 2 * i + 2; } static size_t sift_down(heap_t *h, size_t i) { size_t size = array_size(h->array); void **data = array_data(h->array); bool cond = false; do { size_t largest; size_t l = left(i); size_t r = right(i); if (l < size && h->array->dinfo->cmp(data[l], data[i])) { largest = l; } else { largest = i; } if (r < size && h->array->dinfo->cmp(data[r], data[largest])) { largest = r; } cond = largest != i; if (cond) { CDC_SWAP(void *, data[i], data[largest]); i = largest; } } while (cond); return i; } static size_t sift_up(heap_t *h, size_t i) { void **data = array_data(h->array); size_t p = parent(i); while (i > 0 && h->array->dinfo->cmp(data[i], data[p])) { CDC_SWAP(void *, data[i], data[p]); i = parent(i); p = parent(i); } return i; } static void build_heap(heap_t *h) { size_t i = array_size(h->array) / 2; while (i--) { sift_down(h, i); } } static stat_t init_varg(heap_t *h, va_list args) { void *elem = NULL; while ((elem = va_arg(args, void *)) != CDC_END) { stat_t ret = array_push_back(h->array, elem); if (ret != CDC_STATUS_OK) { return ret; } } build_heap(h); return CDC_STATUS_OK; } stat_t heap_ctor(heap_t **h, data_info_t *info) { assert(h != NULL); assert(CDC_HAS_CMP(info)); heap_t *tmp = (heap_t *)calloc(sizeof(heap_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } stat_t ret = array_ctor(&tmp->array, info); if (ret != CDC_STATUS_OK) { free(tmp); return ret; } *h = tmp; return ret; } stat_t heap_ctorl(heap_t **h, data_info_t *info, ...) { assert(h != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t ret = heap_ctorv(h, info, args); va_end(args); return ret; } stat_t heap_ctorv(heap_t **h, data_info_t *info, va_list args) { assert(h != NULL); assert(CDC_HAS_CMP(info)); stat_t ret = heap_ctor(h, info); if (ret != CDC_STATUS_OK) { return ret; } return init_varg(*h, args); } void heap_dtor(heap_t *h) { assert(h != NULL); array_dtor(h->array); free(h); } void heap_extract_top(heap_t *h) { assert(h != NULL); assert(heap_size(h) > 0); void *elem = array_back(h->array); array_pop_back(h->array); if (array_empty(h->array)) { return; } array_set(h->array, 0, elem); sift_down(h, 0); } void heap_change_key(heap_t *h, heap_iter_t *pos, void *key) { assert(h != NULL); assert(pos != NULL); assert(h->array == pos->container); void **data = array_data(h->array); bool is_sift_down = h->array->dinfo->cmp(data[pos->current], key); array_set(h->array, pos->current, key); if (is_sift_down) { pos->current = sift_down(h, pos->current); } else { pos->current = sift_up(h, pos->current); } } stat_t heap_riinsert(heap_t *h, void *key, heap_iter_t *ret) { assert(h != NULL); stat_t stat = array_push_back(h->array, key); if (stat != CDC_STATUS_OK) { return stat; } size_t i = array_size(h->array) - 1; i = sift_up(h, i); if (ret) { ret->container = h->array; ret->current = i; } return stat; } void heap_swap(heap_t *a, heap_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(array_t *, a->array, b->array); } stat_t heap_merge(heap_t *h, heap_t *other) { assert(h != NULL); assert(other != NULL); stat_t ret = array_append_move(h->array, other->array); if (ret != CDC_STATUS_OK) { return ret; } build_heap(h); return CDC_STATUS_OK; } bool heap_is_heap(heap_t *h) { assert(h != NULL); size_t size = heap_size(h); if (size == 0) { return true; } void **data = array_data(h->array); for (size_t i = 1; i < size; ++i) { if (h->array->dinfo->cmp(data[i], data[parent(i)])) { return false; } } return true; }
maksimandrianov/cdstructures
include/cdcontainers/list.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_list is a struct and functions that provide a doubly * linked list. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_LIST_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_LIST_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @defgroup cdc_list * @brief The cdc_list is a struct and functions that provide a doubly * linked list. * @{ */ /** * @brief The cdc_list_node is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_list_node { struct cdc_list_node *next; struct cdc_list_node *prev; void *data; }; /** * @brief The cdc_lisе is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_list { struct cdc_list_node *head; struct cdc_list_node *tail; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_list_iterator is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_list_iter { struct cdc_list *container; struct cdc_list_node *current; }; /** * @brief The cdc_list_riter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_list_riter { struct cdc_list *container; struct cdc_list_node *current; }; /** * @brief For-each macro. * * Example: * @code{.c} * struct cdc_list *list = NULL; * ... * CDC_LIST_FOR_EACH(node, list) { * // node->data * } * @endcode */ #define CDC_LIST_FOR_EACH(item, list) \ for (struct cdc_list_node * (item) = (list->head); (item); (item) = (item)->next) // Base /** * @defgroup cdc_list_base Base * @{ */ /** * @brief Constructs an empty list. * @param[out] l - cdc_list * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_ctor(struct cdc_list **l, struct cdc_data_info *info); /** * @brief Constructs a list, initialized by an variable number of pointers. * The last pointer must be CDC_END. * @param[out] l - cdc_list * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_list *list = NULL; * if (cdc_list_ctorl(&list, NULL, CDC_FROM_INT(1), * CDC_FROM_INT(2), CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_list_ctorl(struct cdc_list **l, struct cdc_data_info *info, ...); /** * @brief Constructs a list, initialized by args. The last pointer must be CDC_END. * @param[out] l - cdc_list * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_ctorv(struct cdc_list **l, struct cdc_data_info *info, va_list args); /** * @brief Destroys the list. * @param[in] l - cdc_list */ void cdc_list_dtor(struct cdc_list *l); /** @} */ // Element access /** * @defgroup cdc_list_element_access Element access * @{ */ /** * @brief Returns an element at index position index in the list. * @param[in] l - cdc_list * @param[in] index - index of an element to return * @return element from |index| position. */ void *cdc_list_get(struct cdc_list *l, size_t index); /** * @brief Writes to pointer an element from specified position in the list. * Bounds checking is performed. * @param[in] l - cdc_list * @param[in] index - index of an element to write at elem * @param[out] elem - pointer where an element will be written * @return DC_STATUS_OK in a successful case or CDC_STATUS_OUT_OF_RANGE if the * index is incorrect. */ enum cdc_stat cdc_list_at(struct cdc_list *l, size_t index, void **elem); /** * @brief Returns a first element in the list. * @param[in] l - cdc_list * @return first element in the list. */ static inline void *cdc_list_front(struct cdc_list *l) { assert(l != NULL); assert(l->size > 0); return l->head->data; } /** * @brief Returns a last element in the list. * @param[in] l - cdc_list * @return last element in the list. */ static inline void *cdc_list_back(struct cdc_list *l) { assert(l != NULL); assert(l->size > 0); return l->tail->data; } /** @} */ // Capacity /** * @defgroup cdc_list_capacity Capacity * @{ */ /** * @brief Returns the number of elements in the list. * @param[in] l - cdc_list * @return the number of elements in the list. */ static inline size_t cdc_list_size(struct cdc_list *l) { assert(l != NULL); return l->size; } /** * @brief Checks if the list has no elements. * @param[in] l - cdc_list * @return true if the list is empty, false otherwise. */ static inline bool cdc_list_empty(struct cdc_list *l) { assert(l != NULL); return l->size == 0; } /** @} */ // Modifiers /** * @defgroup cdc_list_modifiers Modifiers * @{ */ /** * @brief Sets an element at index position to the value. The function is not * called to free memory. * @param[in] l - cdc_list * @param[in] index - index position where the value will be written * @param[in] value - value */ void cdc_list_set(struct cdc_list *l, size_t index, void *value); /** * @brief Inserts an element at the end of the list. * @param[in] l - cdc_list * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_push_back(struct cdc_list *l, void *value); /** * @brief Removes a last element in the list. * @param[in] l - cdc_list */ void cdc_list_pop_back(struct cdc_list *l); /** * @brief Inserts an element at the beginning of the list. * @param[in] l - cdc_list * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_push_front(struct cdc_list *l, void *value); /** * @brief Removes a first element in the list. * @param[in] l - cdc_list */ void cdc_list_pop_front(struct cdc_list *l); /** * @brief Inserts an element at |index| position in the list. If index is 0, the * value is prepended to the list. If index is cdc_list_size(), the value is * appended to the list. * @param[in] l - cdc_list * @param[in] index - index position where an element will be inserted * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_insert(struct cdc_list *l, size_t index, void *value); /** * @brief Inserts an element in front of the item pointed to by the iterator before. * @param[in] before - iterator position before which an element will be inserted * @param[in] value - value * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_list_iinsert(struct cdc_list_iter *before, void *value); /** * @brief Removes an element at index position in the circular arrray. * @param[in] l - cdc_list * @param[in] index - index position where an element will be removed */ void cdc_list_erase(struct cdc_list *l, size_t index); /** * @brief Removes an element associated with the iterator pos from the list. * @param[in] pos - iterator */ void cdc_list_ierase(struct cdc_list_iter *pos); /** * @brief Removes all the elements from the list. * @param[in] l - cdc_list */ void cdc_list_clear(struct cdc_list *l); /** * @brief Swaps lists a and b. This operation is very fast and never * fails. * @param[in, out] a - cdc_list * @param[in, out] b - cdc_list */ void cdc_list_swap(struct cdc_list *a, struct cdc_list *b); /** @} */ // Operations /** * @defgroup cdc_list_operations Operations * @{ */ /** * @brief Transfers elements from one container, iterators (first, last] to * another container at position before iterator position. * @param[in] position - iterator before which the content will be inserted * @param[in] first, last - range of elements to transfer from other */ void cdc_list_splice(struct cdc_list_iter *position, struct cdc_list_iter *first, struct cdc_list_iter *last); /** * @brief Transfers elements from one container, iterators (first, end] to * another container at position before iterator position. * @param[in] position - iterator before which the content will be inserted * @param[in] first - beginning of the range from which elements will be transferred */ void cdc_list_ssplice(struct cdc_list_iter *position, struct cdc_list_iter *first); /** * @brief Transfers all elements from container other to another container at * position before iterator position. * @param[in] position - iterator before which the content will be inserted * @param[im] other - cdc_list */ void cdc_list_lsplice(struct cdc_list_iter *position, struct cdc_list *other); /** * @brief Merges two sorted lists into one. The lists should be sorted into * ascending order. * @param[in] l - cdc_list * @param[in] other - another cdc_list to merge */ void cdc_list_merge(struct cdc_list *l, struct cdc_list *other); /** * @brief Merges two sorted lists into one. The lists should be sorted. * @param[in] l - cdc_list * @param[in] other - another cdc_list to merge * @param[in] compare - comparison function */ void cdc_list_cmerge(struct cdc_list *l, struct cdc_list *other, cdc_binary_pred_fn_t compare); /** * @brief Removes from the container all elements for which predicate pred * returns true. * @param[in] l - cdc_list * @param[in] pred - unary predicate which returns ​true if the element should be * removed */ void cdc_list_erase_if(struct cdc_list *l, cdc_unary_pred_fn_t pred); /** * @brief Reverses the order of elements in the container. * @param[in] l - cdc_list */ void cdc_list_reverse(struct cdc_list *l); /** * @brief Removes all consecutive duplicate elements from the container. Only * the first element in each group of equal elements is left. * @param[in] l - cdc_list */ void cdc_list_unique(struct cdc_list *l); /** * @brief Removes all consecutive duplicate elements from the container. Only * the first element in each group of equal elements is left. * @param[in] l - cdc_list * @param[in] pred - binary predicate which returns ​true if the elements should * be treated as equal. */ void cdc_list_punique(struct cdc_list *l, cdc_binary_pred_fn_t pred); /** * @brief Sorts elements in ascending order. * @param[in] l - cdc_list */ void cdc_list_sort(struct cdc_list *l); /** * @brief Sorts elements in ascending order. * @param[in] l - cdc_list * @param[in] compare - comparison function object which returns ​true if the * first argument is less than (i.e. is ordered before) the second. */ void cdc_list_csort(struct cdc_list *l, cdc_binary_pred_fn_t compare); /** * @brief A function |cb| is applied to each item of the list. */ void cdc_list_foreach(struct cdc_list *l, void (*cb)(void *)); /** @} */ // Iterators /** * @defgroup cdc_avl_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param[in] l - cdc_list * @param[out] it - cdc_list_iter */ static inline void cdc_list_begin(struct cdc_list *l, struct cdc_list_iter *it) { assert(l != NULL); assert(it != NULL); it->container = l; it->current = l->head; } /** * @brief Initializes the iterator to the end. * @param[in] l - cdc_list * @param[out] it - cdc_list_iter */ static inline void cdc_list_end(struct cdc_list *l, struct cdc_list_iter *it) { assert(l != NULL); assert(it != NULL); it->container = l; it->current = NULL; } /** * @brief Initializes the reverse iterator to the beginning. * @param[in] l - cdc_list * @param[out] it - cdc_list_riter */ static inline void cdc_list_rbegin(struct cdc_list *l, struct cdc_list_riter *it) { assert(l != NULL); assert(it != NULL); it->container = l; it->current = l->tail; } /** * @brief Initializes the reverse iterator to the end. * @param[in] l - cdc_list * @param[out] it - cdc_list_riter */ static inline void cdc_list_rend(struct cdc_list *l, struct cdc_list_riter *it) { assert(l != NULL); assert(it != NULL); it->container = l; it->current = NULL; } /** @} */ // Iterators /** * @defgroup cdc_list_iter * @brief The cdc_list_iter is a struct and functions that provide a list iterator. * @{ */ /** * @brief Advances the iterator to the next element in the list. * @param[in] it - iterator */ static inline void cdc_list_iter_next(struct cdc_list_iter *it) { assert(it != NULL); it->current = it->current->next; } /** * @brief Advances the iterator to the previous element in the list. * @param[in] it - iterator */ static inline void cdc_list_iter_prev(struct cdc_list_iter *it) { assert(it != NULL); it->current = it->current ? it->current->prev : it->container->tail; } /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_list_iter_has_next(struct cdc_list_iter *it) { assert(it != NULL); return it->current->next != NULL; } /** * @brief Returns true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. */ static inline bool cdc_list_iter_has_prev(struct cdc_list_iter *it) { assert(it != NULL); return it->current->prev != NULL; } /** * @brief Returns a current element. * @param[in] it - iterator */ static inline void *cdc_list_iter_data(struct cdc_list_iter *it) { assert(it != NULL); return it->current->data; } /** * @brief Сasts reverse iterator to iterator. * @param[in] rit - reverse iterator * @param[out] it - iterator */ static inline void cdc_list_iter_from(struct cdc_list_riter *rit, struct cdc_list_iter *it) { assert(rit != NULL); assert(it != NULL); it->container = rit->container; it->current = rit->current ? rit->current->next : rit->container->head; } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_list_iter_is_eq(struct cdc_list_iter *it1, struct cdc_list_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->current == it2->current; } /** * @brief Advances the reverse iterator to the next element in the list. * @param[in] it - reverse iterator */ static inline void cdc_list_riter_next(struct cdc_list_riter *it) { assert(it != NULL); it->current = it->current->prev; } /** * @brief Advances the reverse iterator to the previous element in the list. * @param[in] it - reverse iterator */ static inline void cdc_list_riter_prev(struct cdc_list_riter *it) { assert(it != NULL); it->current = it->current ? it->current->next : it->container->head; } /** * @brief Returns true if there is at least one item ahead of the reverse * iterator, i.e. the reverse iterator is not at the back of the container. * otherwise returns false. * @param[in] it - reverse iterator * @return true if there is at least one item ahead of the reverse * iterator, i.e. the reverse iterator is not at the back of the container. */ static inline bool cdc_list_riter_has_next(struct cdc_list_riter *it) { assert(it != NULL); return it->current->prev != NULL; } /** * @brief Returns true if there is at least one item behind the reverse * iterator, i.e. the reverse iterator is not at the front of the container; * otherwise returns false. * @param[in] it - reverse iterator * @return true if there is at least one item behind the reverse * iterator, i.e. the reverse iterator is not at the front of the container; * otherwise returns false. */ static inline bool cdc_list_riter_has_prev(struct cdc_list_riter *it) { assert(it != NULL); return it->current->next != NULL; } /** * @brief Returns a current element. * @param[in] it - reverse iterator */ static inline void *cdc_list_riter_data(struct cdc_list_riter *it) { assert(it != NULL); return it->current->data; } /** * @brief Сasts iterator to reverse iterator * @param[in] it - iterator * @param[out] rit - reverse iterator */ static inline void cdc_list_riter_from(struct cdc_list_iter *it, struct cdc_list_riter *rit) { assert(it != NULL); assert(rit != NULL); rit->container = it->container; rit->current = it->current ? it->current->prev : it->container->tail; } /** * @brief Returns false if the reverse iterator |rit1| equal to the reverse * iterator |rit2|, otherwise returns false. * @param[in] rit1 - reverse iterator * @param[in] rit2 - reverse iterator */ static inline bool cdc_list_riter_is_eq(struct cdc_list_riter *rit1, struct cdc_list_riter *rit2) { assert(rit1 != NULL); assert(rit2 != NULL); return rit1->container == rit2->container && rit1->current == rit2->current; } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_list_node list_node_t; typedef struct cdc_list list_t; typedef struct cdc_list_iter list_iter_t; typedef struct cdc_list_riter list_riter_t; // Base #define list_ctor(...) cdc_list_ctor(__VA_ARGS__) #define list_ctorl(...) cdc_list_ctorl(__VA_ARGS__) #define list_ctorv(...) cdc_list_ctorv(__VA_ARGS__) #define list_dtor(...) cdc_list_dtor(__VA_ARGS__) // Element access #define list_at(...) cdc_list_at(__VA_ARGS__) #define list_front(...) cdc_list_front(__VA_ARGS__) #define list_back(...) cdc_list_back(__VA_ARGS__) #define list_get(...) cdc_list_get(__VA_ARGS__) // Capacity #define list_empty(...) cdc_list_empty(__VA_ARGS__) #define list_size(...) cdc_list_size(__VA_ARGS__) // Modifiers #define list_set(...) cdc_list_set(__VA_ARGS__) #define list_insert(...) cdc_list_insert(__VA_ARGS__) #define list_iinsert(...) cdc_list_iinsert(__VA_ARGS__) #define list_erase(...) cdc_list_erase(__VA_ARGS__) #define list_ierase(...) cdc_list_ierase(__VA_ARGS__) #define list_clear(...) cdc_list_clear(__VA_ARGS__) #define list_push_back(...) cdc_list_push_back(__VA_ARGS__) #define list_pop_back(...) cdc_list_pop_back(__VA_ARGS__) #define list_push_front(...) cdc_list_push_front(__VA_ARGS__) #define list_pop_front(...) cdc_list_pop_front(__VA_ARGS__) #define list_swap(...) cdc_list_swap(__VA_ARGS__) // Operations #define list_splice(...) cdc_list_splice(__VA_ARGS__) #define list_ssplice(...) cdc_list_ssplice(__VA_ARGS__) #define list_lsplice(...) cdc_list_lsplice(__VA_ARGS__) #define list_merge(...) cdc_list_merge(__VA_ARGS__) #define list_cmerge(...) cdc_list_cmerge(__VA_ARGS__) #define list_erase_if(...) cdc_list_erase_if(__VA_ARGS__) #define list_reverse(...) cdc_list_reverse(__VA_ARGS__) #define list_unique(...) cdc_list_unique(__VA_ARGS__) #define list_punique(...) cdc_list_punique(__VA_ARGS__) #define list_sort(...) cdc_list_sort(__VA_ARGS__) #define list_csort(...) cdc_list_csort(__VA_ARGS__) #define list_foreach(...) cdc_list_foreach(__VA_ARGS__) // Iterators #define list_begin(...) cdc_list_begin(__VA_ARGS__) #define list_end(...) cdc_list_end(__VA_ARGS__) #define list_rbegin(...) cdc_list_rbegin(__VA_ARGS__) #define list_rend(...) cdc_list_rend(__VA_ARGS__) // Iterators #define list_iter_next(...) cdc_list_iter_next(__VA_ARGS__) #define list_iter_prev(...) cdc_list_iter_prev(__VA_ARGS__) #define list_iter_has_next(...) cdc_list_iter_has_next(__VA_ARGS__) #define list_iter_has_prev(...) cdc_list_iter_has_prev(__VA_ARGS__) #define list_iter_data(...) cdc_list_iter_data(__VA_ARGS__) #define list_riter_from(...) cdc_list_riter_from(__VA_ARGS__) #define list_iter_is_eq(...) cdc_list_iter_is_eq(__VA_ARGS__) #define list_riter_next(...) cdc_list_riter_next(__VA_ARGS__) #define list_riter_prev(...) cdc_list_riter_prev(__VA_ARGS__) #define list_riter_has_next(...) cdc_list_riter_has_next(__VA_ARGS__) #define list_riter_has_prev(...) cdc_list_riter_has_prev(__VA_ARGS__) #define list_riter_data(...) cdc_list_riter_data(__VA_ARGS__) #define list_iter_from(...) cdc_list_iter_from(__VA_ARGS__) #define list_riter_is_eq(...) cdc_list_riter_is_eq(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_LIST_H
maksimandrianov/cdstructures
src/splay-tree.c
<reponame>maksimandrianov/cdstructures<filename>src/splay-tree.c // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/splay-tree.h" #include "cdcontainers/data-info.h" #include "cdcontainers/tree-utils.h" #include <stdint.h> #include <stdlib.h> #include <string.h> struct node_pair { splay_tree_node_t *left; splay_tree_node_t *right; }; CDC_MAKE_FIND_NODE_FN(splay_tree_node_t *) CDC_MAKE_MIN_NODE_FN(splay_tree_node_t *) CDC_MAKE_MAX_NODE_FN(splay_tree_node_t *) CDC_MAKE_SUCCESSOR_FN(splay_tree_node_t *) CDC_MAKE_PREDECESSOR_FN(splay_tree_node_t *) static splay_tree_node_t *make_new_node(void *key, void *val) { splay_tree_node_t *node = (splay_tree_node_t *)malloc(sizeof(splay_tree_node_t)); if (node) { node->key = key; node->value = val; node->parent = node->left = node->right = NULL; } return node; } static void free_node(splay_tree_t *t, splay_tree_node_t *node) { assert(t != NULL); if (CDC_HAS_DFREE(t->dinfo)) { pair_t pair = {node->key, node->value}; t->dinfo->dfree(&pair); } free(node); } static void free_splay_tree(splay_tree_t *t, splay_tree_node_t *root) { assert(t != NULL); if (root == NULL) { return; } free_splay_tree(t, root->left); free_splay_tree(t, root->right); free_node(t, root); } static void update_link(splay_tree_node_t *parent, splay_tree_node_t *old, splay_tree_node_t *node) { if (!parent) { return; } if (parent->left == old) { parent->left = node; } else { parent->right = node; } } static splay_tree_node_t *zig_right(splay_tree_node_t *node) { splay_tree_node_t *p = node->parent; update_link(p->parent, p, node); node->parent = p->parent; p->left = node->right; if (p->left) { p->left->parent = p; } node->right = p; if (node->right) { node->right->parent = node; } return node; } static splay_tree_node_t *zig_left(splay_tree_node_t *node) { splay_tree_node_t *p = node->parent; update_link(p->parent, p, node); node->parent = p->parent; p->right = node->left; if (p->right) { p->right->parent = p; } node->left = p; if (node->left) { node->left->parent = node; } return node; } static splay_tree_node_t *zigzig_right(splay_tree_node_t *node) { node = zig_right(node->parent); return zig_right(node->left); } static splay_tree_node_t *zigzig_left(splay_tree_node_t *node) { node = zig_left(node->parent); return zig_left(node->right); } static splay_tree_node_t *zigzag_right(splay_tree_node_t *node) { node = zig_left(node); return zig_right(node); } static splay_tree_node_t *zigzag_left(splay_tree_node_t *node) { node = zig_right(node); return zig_left(node); } static splay_tree_node_t *splay(splay_tree_node_t *node) { while (node->parent) { if (node->parent->parent == NULL) { if (node == node->parent->left) { node = zig_right(node); } else { node = zig_left(node); } } else if (node == node->parent->left) { if (node->parent == node->parent->parent->left) { node = zigzig_right(node); } else { node = zigzag_left(node); } } else { if (node->parent == node->parent->parent->right) { node = zigzig_left(node); } else { node = zigzag_right(node); } } } return node; } static splay_tree_node_t *find_hint(splay_tree_node_t *node, void *key, cdc_binary_pred_fn_t compar) { splay_tree_node_t *tmp = node; while (node) { if (compar(key, node->key)) { if (node->left) { node = node->left; } else { break; } } else if (compar(node->key, key)) { if (node->right) { node = node->right; } else { break; } } else { break; } } return node ? node : cdc_max_tree_node(tmp); } static struct node_pair split(splay_tree_node_t *node, void *key, cdc_binary_pred_fn_t compar) { struct node_pair ret; node = splay(node); if (compar(key, node->key)) { ret.left = node->left; ret.right = node; node->left = NULL; if (ret.left) { ret.left->parent = NULL; } } else { ret.left = node; ret.right = node->right; node->right = NULL; if (ret.right) { ret.right->parent = NULL; } } return ret; } static splay_tree_node_t *merge(splay_tree_node_t *a, splay_tree_node_t *b) { if (!a) { return b; } if (!b) { return a; } a = cdc_max_tree_node(a); a = splay(a); a->right = b; b->parent = a; return a; } static splay_tree_node_t *sfind(splay_tree_t *t, void *key) { splay_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (!node) { return node; } node = splay(node); t->root = node; return node; } static splay_tree_node_t *insert_unique(splay_tree_t *t, splay_tree_node_t *node, splay_tree_node_t *nearest) { struct node_pair pair; if (t->root == NULL) { t->root = node; } else { pair = split(nearest, node->key, t->dinfo->cmp); node->left = pair.left; if (node->left) { node->left->parent = node; } node->right = pair.right; if (node->right) { node->right->parent = node; } t->root = node; } ++t->size; return node; } static stat_t init_varg(splay_tree_t *t, va_list args) { pair_t *pair = NULL; while ((pair = va_arg(args, pair_t *)) != CDC_END) { stat_t stat = splay_tree_insert(t, pair->first, pair->second, NULL); if (stat != CDC_STATUS_OK) { return stat; } } return CDC_STATUS_OK; } stat_t splay_tree_ctor(splay_tree_t **t, data_info_t *info) { assert(t != NULL); assert(CDC_HAS_CMP(info)); splay_tree_t *tmp = (splay_tree_t *)calloc(sizeof(splay_tree_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } if (info && !(tmp->dinfo = di_shared_ctorc(info))) { free(tmp); return CDC_STATUS_BAD_ALLOC; } *t = tmp; return CDC_STATUS_OK; } stat_t splay_tree_ctorl(splay_tree_t **t, data_info_t *info, ...) { assert(t != NULL); assert(CDC_HAS_CMP(info)); va_list args; va_start(args, info); stat_t stat = splay_tree_ctorv(t, info, args); va_end(args); return stat; } stat_t splay_tree_ctorv(splay_tree_t **t, data_info_t *info, va_list args) { assert(t != NULL); assert(CDC_HAS_CMP(info)); stat_t stat = splay_tree_ctor(t, info); if (stat != CDC_STATUS_OK) { return stat; } return init_varg(*t, args); } void splay_tree_dtor(splay_tree_t *t) { assert(t != NULL); free_splay_tree(t, t->root); di_shared_dtor(t->dinfo); free(t); } stat_t splay_tree_get(splay_tree_t *t, void *key, void **value) { assert(t != NULL); splay_tree_node_t *node = sfind(t, key); if (node) { *value = node->value; } return node ? CDC_STATUS_OK : CDC_STATUS_NOT_FOUND; } size_t splay_tree_count(splay_tree_t *t, void *key) { assert(t != NULL); return (size_t)(sfind(t, key) != NULL); } void splay_tree_find(splay_tree_t *t, void *key, splay_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); splay_tree_node_t *node = sfind(t, key); if (!node) { splay_tree_end(t, it); return; } it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } stat_t splay_tree_insert(splay_tree_t *t, void *key, void *value, pair_splay_tree_iter_bool_t *ret) { assert(t != NULL); splay_tree_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return splay_tree_insert1(t, key, value, it, inserted); } stat_t splay_tree_insert1(splay_tree_t *t, void *key, void *value, splay_tree_iter_t *it, bool *inserted) { assert(t != NULL); splay_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp); bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key); if (!finded) { splay_tree_node_t *new_node = make_new_node(key, value); if (!new_node) { return CDC_STATUS_BAD_ALLOC; } node = insert_unique(t, new_node, node); } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } stat_t splay_tree_insert_or_assign(splay_tree_t *t, void *key, void *value, pair_splay_tree_iter_bool_t *ret) { assert(t != NULL); splay_tree_iter_t *it = NULL; bool *inserted = NULL; if (ret) { it = &ret->first; inserted = &ret->second; } return splay_tree_insert_or_assign1(t, key, value, it, inserted); } stat_t splay_tree_insert_or_assign1(splay_tree_t *t, void *key, void *value, splay_tree_iter_t *it, bool *inserted) { assert(t != NULL); splay_tree_node_t *node = find_hint(t->root, key, t->dinfo->cmp); bool finded = node && cdc_eq(t->dinfo->cmp, node->key, key); if (!finded) { splay_tree_node_t *new_node = make_new_node(key, value); if (!new_node) { return CDC_STATUS_BAD_ALLOC; } node = insert_unique(t, new_node, node); } else { node->value = value; } if (it) { it->container = t; it->current = node; it->prev = cdc_tree_predecessor(node); } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } size_t splay_tree_erase(splay_tree_t *t, void *key) { assert(t != NULL); splay_tree_node_t *node = cdc_find_tree_node(t->root, key, t->dinfo->cmp); if (!node) { return 0; } node = splay(node); if (node->left) { node->left->parent = NULL; } if (node->right) { node->right->parent = NULL; } t->root = merge(node->left, node->right); free_node(t, node); --t->size; return 1; } void splay_tree_clear(splay_tree_t *t) { assert(t != NULL); free_splay_tree(t, t->root); t->size = 0; t->root = NULL; } void splay_tree_swap(splay_tree_t *a, splay_tree_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(splay_tree_node_t *, a->root, b->root); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } void splay_tree_begin(splay_tree_t *t, splay_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = cdc_min_tree_node(t->root); it->prev = NULL; } void splay_tree_end(splay_tree_t *t, splay_tree_iter_t *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = NULL; it->prev = cdc_max_tree_node(t->root); } void splay_tree_iter_next(splay_tree_iter_t *it) { assert(it != NULL); it->prev = it->current; it->current = cdc_tree_successor(it->current); } void splay_tree_iter_prev(splay_tree_iter_t *it) { assert(it != NULL); it->current = it->prev; it->prev = cdc_tree_predecessor(it->current); }
maksimandrianov/cdstructures
src/tables/seq-circular-array.c
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/circular-array.h" #include "cdcontainers/tables/isequence.h" #include <assert.h> static stat_t ctor(void **cntr, data_info_t *info) { assert(cntr != NULL); circular_array_t **circular_array = (circular_array_t **)cntr; return circular_array_ctor(circular_array, info); } static stat_t ctorv(void **cntr, data_info_t *info, va_list args) { assert(cntr != NULL); circular_array_t **circular_array = (circular_array_t **)cntr; return circular_array_ctorv(circular_array, info, args); } static void dtor(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_dtor(circular_array); } static void *front(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_front(circular_array); } static void *back(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_back(circular_array); } static bool empty(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_empty(circular_array); } static size_t size(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_size(circular_array); } static stat_t push_back(void *cntr, void *elem) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_push_back(circular_array, elem); } static void pop_back(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_pop_back(circular_array); } static stat_t push_front(void *cntr, void *elem) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_push_front(circular_array, elem); } static void pop_front(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_pop_front(circular_array); } static stat_t insert(void *cntr, size_t index, void *value) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_insert(circular_array, index, value); } static void erase(void *cntr, size_t index) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_erase(circular_array, index); } static void clear(void *cntr) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_clear(circular_array); } static void *get(void *cntr, size_t index) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; return circular_array_get(circular_array, index); } static void set(void *cntr, size_t index, void *value) { assert(cntr != NULL); circular_array_t *circular_array = (circular_array_t *)cntr; circular_array_set(circular_array, index, value); } static const sequence_table_t _table = {.ctor = ctor, .ctorv = ctorv, .dtor = dtor, .front = front, .back = back, .empty = empty, .size = size, .push_back = push_back, .pop_back = pop_back, .push_front = push_front, .pop_front = pop_front, .insert = insert, .erase = erase, .clear = clear, .get = get, .set = set}; const sequence_table_t *cdc_seq_carray = &_table;
maksimandrianov/cdstructures
include/cdcontainers/common.h
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_COMMON_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_COMMON_H #include <cdcontainers/casts.h> #include <cdcontainers/hash.h> #include <stdbool.h> #include <stddef.h> #define CDC_END CDC_FROM_INT(UINTPTR_MAX) #define CDC_MAX(a, b) ((a) > (b) ? (a) : (b)) #define CDC_MIN(a, b) ((a) < (b) ? (a) : (b)) #define CDC_ABS(x) ((x < 0) ? -(x) : x) #define CDC_ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) #define CDC_SWAP(T, x, y) \ do { \ T tmp = x; \ x = y; \ y = tmp; \ } while (0) #define CDC_INIT_STRUCT \ { \ 0, \ } #define CDC_STATIC_ASSERT(COND, MSG) typedef char cdc_static_assertion_##MSG[(COND) ? 1 : -1] typedef void (*cdc_free_fn_t)(void *); typedef int (*cdc_unary_pred_fn_t)(const void *); typedef int (*cdc_binary_pred_fn_t)(const void *, const void *); typedef void (*cdc_copy_fn_t)(void *, const void *); struct cdc_pair { void *first; void *second; }; /** * @brief The cdc_data_info struct used to initialize contaners. * * This gives more data about the data stored in the container. * */ struct cdc_data_info { /** * @brief dfree - callback free data. * * If this function is not NULL, then it will be automatically applied to free * memory for cotainer items. */ cdc_free_fn_t dfree; /** * @brief cmp - callback less or greater. * * Used for containers where check for less or greater is required. * For example, for a cdc_map. */ cdc_binary_pred_fn_t cmp; /** * @brief eq - callback equil. * * Used for containers where equality check is required. For example, for a * cdc_hash_table. */ cdc_binary_pred_fn_t eq; cdc_hash_fn_t hash; cdc_copy_fn_t cp; size_t size; /** * @brief __cnt * * To avoid problems, do not change this field in the code. */ size_t __cnt; }; static inline size_t cdc_up_to_pow2(size_t x) { x = x - 1; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } enum cdc_iterator_type { // Forward iterator category. CDC_FWD_ITERATOR, // Bidirectional iterator category. CDC_BIDIR_ITERATOR, // Random-access iterator category. CDC_RA_ITERATOR }; // Short names #ifdef CDC_USE_SHORT_NAMES typedef enum cdc_iterator_type iterator_type_t; typedef struct cdc_pair pair_t; typedef struct cdc_data_info data_info_t; #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_COMMON_H
maksimandrianov/cdstructures
tests/test-priority-queueh.c
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/adapters/priority-queue.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include <assert.h> #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> static int gt(const void *a, const void *b) { return CDC_TO_INT(a) > CDC_TO_INT(b); } void test_priority_queue_ctor() { priority_queue_t *q = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(priority_queue_ctor(cdc_pq_heap, &q, &info), CDC_STATUS_OK); CU_ASSERT(priority_queue_empty(q)); priority_queue_dtor(q); } void test_priority_queue_ctorl() { priority_queue_t *h = NULL; int a = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL( priority_queue_ctorl(cdc_pq_heap, &h, &info, CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(priority_queue_size(h), 2); CU_ASSERT(CDC_TO_INT(priority_queue_top(h)) == a); priority_queue_pop(h); CU_ASSERT_EQUAL(priority_queue_size(h), 1); CU_ASSERT(CDC_TO_INT(priority_queue_top(h)) == a); priority_queue_pop(h); CU_ASSERT(priority_queue_empty(h)); priority_queue_dtor(h); } void test_priority_queue_push() { priority_queue_t *h = NULL; int a = 0, b = 1, c = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(priority_queue_ctor(cdc_pq_heap, &h, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(priority_queue_push(h, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(priority_queue_size(h), 1); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), a); CU_ASSERT_EQUAL(priority_queue_push(h, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(priority_queue_size(h), 2); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), c); CU_ASSERT_EQUAL(priority_queue_push(h, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(priority_queue_size(h), 3); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), c); priority_queue_dtor(h); } void test_priority_queue_pop() { priority_queue_t *h = NULL; int a = 0, b = 3, c = 2, d = 1; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(priority_queue_ctorl(cdc_pq_heap, &h, &info, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), b); priority_queue_pop(h); CU_ASSERT_EQUAL(priority_queue_size(h), 3); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), c); priority_queue_pop(h); CU_ASSERT_EQUAL(priority_queue_size(h), 2); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), d); priority_queue_pop(h); CU_ASSERT_EQUAL(priority_queue_size(h), 1); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), a); priority_queue_pop(h); CU_ASSERT(priority_queue_empty(h)); priority_queue_dtor(h); } void test_priority_queue_top() { priority_queue_t *h = NULL; int a = 1, b = 10, c = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(priority_queue_ctorl(cdc_pq_heap, &h, &info, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(h)), b); priority_queue_dtor(h); } void test_priority_queue_swap() { priority_queue_t *v = NULL, *w = NULL; int a = 2, b = 3, c = 4; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(priority_queue_ctorl(cdc_pq_heap, &v, &info, CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL( priority_queue_ctorl(cdc_pq_heap, &w, &info, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); priority_queue_swap(v, w); CU_ASSERT_EQUAL(priority_queue_size(v), 2); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(v)), c); CU_ASSERT_EQUAL(priority_queue_size(w), 1); CU_ASSERT_EQUAL(CDC_TO_INT(priority_queue_top(w)), b); priority_queue_dtor(v); priority_queue_dtor(w); }
maksimandrianov/cdstructures
src/tables/pqueue-pairing-heap.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/pairing-heap.h" #include "cdcontainers/tables/ipqueue.h" #include <assert.h> static stat_t ctor(void **cntr, data_info_t *info) { assert(cntr != NULL); pairing_heap_t **heap = (pairing_heap_t **)cntr; return pairing_heap_ctor(heap, info); } static stat_t ctorv(void **cntr, data_info_t *info, va_list args) { assert(cntr != NULL); pairing_heap_t **heap = (pairing_heap_t **)cntr; return pairing_heap_ctorv(heap, info, args); } static void dtor(void *cntr) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; pairing_heap_dtor(heap); } static void *top(void *cntr) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; return pairing_heap_top(heap); } static bool empty(void *cntr) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; return pairing_heap_empty(heap); } static size_t size(void *cntr) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; return pairing_heap_size(heap); } static stat_t push(void *cntr, void *elem) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; return pairing_heap_insert(heap, elem); } static void pop(void *cntr) { assert(cntr != NULL); pairing_heap_t *heap = (pairing_heap_t *)cntr; pairing_heap_extract_top(heap); } static const priority_queue_table_t _table = {.ctor = ctor, .ctorv = ctorv, .dtor = dtor, .top = top, .empty = empty, .size = size, .push = push, .pop = pop}; const priority_queue_table_t *cdc_pq_pheap = &_table;
maksimandrianov/cdstructures
tests/test-binomial-heap.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/binomial-heap.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include "cdcontainers/global.h" #include <assert.h> #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> static int gt(const void *a, const void *b) { return CDC_TO_INT(a) > CDC_TO_INT(b); } static size_t g_count_free = 0; static void test_free(void *ptr) { CDC_UNUSED(ptr); ++g_count_free; } static inline void heap_int_print(binomial_heap_node_t *node) { while (node) { printf("%d ", CDC_TO_INT(node->key)); heap_int_print(node->child); node = node->sibling; } } void test_binomial_heap_ctor() { binomial_heap_t *h = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctor(&h, &info), CDC_STATUS_OK); CU_ASSERT(binomial_heap_empty(h)); binomial_heap_dtor(h); } void test_binomial_heap_ctorl() { binomial_heap_t *h = NULL; int a = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctorl(&h, &info, CDC_FROM_INT(a), CDC_FROM_INT(a), CDC_END), CDC_STATUS_OK); CU_ASSERT(binomial_heap_is_heap(h)); CU_ASSERT_EQUAL(binomial_heap_size(h), 2); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), a); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 1); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), a); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT(binomial_heap_empty(h)); binomial_heap_dtor(h); } void test_binomial_heap_dtor() { binomial_heap_t *h = NULL; const int count = 9; data_info_t info = CDC_INIT_STRUCT; info.dfree = test_free; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctor(&h, &info), CDC_STATUS_OK); for (int i = count; i > 0; --i) CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(i)), CDC_STATUS_OK); for (int i = 0; i < count / 2; ++i) CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(i)), CDC_STATUS_OK); CU_ASSERT(binomial_heap_is_heap(h)); CU_ASSERT_EQUAL(binomial_heap_size(h), count + count / 2); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), count); binomial_heap_dtor(h); CU_ASSERT_EQUAL(g_count_free, count + count / 2); g_count_free = 0; } void test_binomial_heap_top() { binomial_heap_t *h = NULL; int a = 1, b = 10, c = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL( binomial_heap_ctorl(&h, &info, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), b); binomial_heap_dtor(h); } void test_binomial_heap_extract_top() { binomial_heap_t *h = NULL; int a = 0, b = 3, c = 2, d = 1; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctorl(&h, &info, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), b); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 3); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), c); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 2); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), d); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 1); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), a); CU_ASSERT_EQUAL(binomial_heap_extract_top(h), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 0); binomial_heap_dtor(h); } void test_binomial_heap_insert() { binomial_heap_t *h = NULL; int a = 0, b = 1, c = 2; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctor(&h, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 1); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), a); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 2); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), c); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_size(h), 3); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), c); binomial_heap_dtor(h); } void test_binomial_heap_change_key() { binomial_heap_t *h = NULL; binomial_heap_iter_t iter1 = CDC_INIT_STRUCT; int a = 0, b = 4, c = 3, d = 1; int n = 2, max_key = 10, min_key = -1; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctorl(&h, &info, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_riinsert(h, CDC_FROM_INT(n), &iter1), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_insert(h, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT(binomial_heap_is_heap(h)); binomial_heap_change_key(h, &iter1, CDC_FROM_INT(max_key)); CU_ASSERT(binomial_heap_is_heap(h)); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), max_key); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_iter_data(&iter1)), max_key); binomial_heap_change_key(h, &iter1, CDC_FROM_INT(min_key)); CU_ASSERT(binomial_heap_is_heap(h)); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(h)), b); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_iter_data(&iter1)), min_key); binomial_heap_dtor(h); } void test_binomial_heap_merge() { binomial_heap_t *v = NULL, *w = NULL; int a = 2, b = 3, c = 4; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctorl(&v, &info, CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_ctorl(&w, &info, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); binomial_heap_merge(v, w); CU_ASSERT(binomial_heap_is_heap(v)); CU_ASSERT_EQUAL(binomial_heap_size(v), 3); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(v)), 4); CU_ASSERT(binomial_heap_empty(w)); binomial_heap_dtor(v); binomial_heap_dtor(w); } void test_binomial_heap_swap() { binomial_heap_t *v = NULL, *w = NULL; int a = 2, b = 3, c = 4; data_info_t info = CDC_INIT_STRUCT; info.cmp = gt; CU_ASSERT_EQUAL(binomial_heap_ctorl(&v, &info, CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(binomial_heap_ctorl(&w, &info, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); binomial_heap_swap(v, w); CU_ASSERT_EQUAL(binomial_heap_size(v), 2); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(v)), c); CU_ASSERT_EQUAL(binomial_heap_size(w), 1); CU_ASSERT_EQUAL(CDC_TO_INT(binomial_heap_top(w)), b); binomial_heap_dtor(v); binomial_heap_dtor(w); }
maksimandrianov/cdstructures
tests/test-splay-tree.c
<reponame>maksimandrianov/cdstructures // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include "cdcontainers/splay-tree.h" #include "cdcontainers/tree-utils.h" #include <float.h> #include <math.h> #include <stdarg.h> #include <CUnit/Basic.h> CDC_MAKE_TREE_HEIGTH_FN(splay_tree_node_t *) static pair_t a = {CDC_FROM_INT(0), CDC_FROM_INT(0)}; static pair_t b = {CDC_FROM_INT(1), CDC_FROM_INT(1)}; static pair_t c = {CDC_FROM_INT(2), CDC_FROM_INT(2)}; static pair_t d = {CDC_FROM_INT(3), CDC_FROM_INT(3)}; static pair_t e = {CDC_FROM_INT(4), CDC_FROM_INT(4)}; static pair_t f = {CDC_FROM_INT(5), CDC_FROM_INT(5)}; static pair_t g = {CDC_FROM_INT(6), CDC_FROM_INT(6)}; static pair_t h = {CDC_FROM_INT(7), CDC_FROM_INT(7)}; static int lt(const void *l, const void *r) { return CDC_TO_INT(l) < CDC_TO_INT(r); } static bool splay_tree_key_int_eq(splay_tree_t *t, size_t count, ...) { va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { pair_t *val = va_arg(args, pair_t *); void *tmp = NULL; if (splay_tree_get(t, val->first, &tmp) != CDC_STATUS_OK || tmp != val->second) { va_end(args); return false; } } va_end(args); return true; } static inline void splay_tree_inorder_print_int(splay_tree_node_t *node) { if (node->left) { splay_tree_inorder_print_int(node->left); } printf("%d ", CDC_TO_INT(node->key)); if (node->right) { splay_tree_inorder_print_int(node->right); } } void test_splay_tree_ctor() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT(splay_tree_empty(t)); splay_tree_dtor(t); } void test_splay_tree_ctorl() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &g, &h, &d, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 4); CU_ASSERT(splay_tree_key_int_eq(t, 4, &a, &g, &h, &d)); splay_tree_dtor(t); } void test_splay_tree_get() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 8); CU_ASSERT(splay_tree_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); void *value = NULL; CU_ASSERT_EQUAL(splay_tree_get(t, CDC_FROM_INT(10), &value), CDC_STATUS_NOT_FOUND); splay_tree_dtor(t); } void test_splay_tree_count() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 2); CU_ASSERT_EQUAL(splay_tree_count(t, a.first), 1); CU_ASSERT_EQUAL(splay_tree_count(t, b.first), 1); CU_ASSERT_EQUAL(splay_tree_count(t, CDC_FROM_INT(10)), 0); splay_tree_dtor(t); } void test_splay_tree_find() { splay_tree_t *t = NULL; splay_tree_iter_t it = CDC_INIT_STRUCT; splay_tree_iter_t it_end = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, CDC_END), CDC_STATUS_OK); splay_tree_find(t, a.first, &it); CU_ASSERT_EQUAL(splay_tree_iter_value(&it), a.second); splay_tree_find(t, b.first, &it); CU_ASSERT_EQUAL(splay_tree_iter_value(&it), b.second); splay_tree_find(t, g.first, &it); CU_ASSERT_EQUAL(splay_tree_iter_value(&it), g.second); splay_tree_find(t, h.first, &it); splay_tree_end(t, &it_end); CU_ASSERT(splay_tree_iter_is_eq(&it, &it_end)); splay_tree_dtor(t); } void test_splay_tree_clear() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 2); splay_tree_clear(t); CU_ASSERT(splay_tree_empty(t)); splay_tree_clear(t); CU_ASSERT(splay_tree_empty(t)); splay_tree_dtor(t); } void test_splay_tree_insert() { splay_tree_t *t = NULL; const int kCount = 100; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctor(&t, &info), CDC_STATUS_OK); for (int i = 0; i < kCount; ++i) { CU_ASSERT_EQUAL(splay_tree_insert(t, CDC_FROM_INT(i), CDC_FROM_INT(i), NULL), CDC_STATUS_OK); } CU_ASSERT_EQUAL(splay_tree_size(t), kCount); for (int i = 0; i < kCount; ++i) { void *val = NULL; CU_ASSERT_EQUAL(splay_tree_get(t, CDC_FROM_INT(i), &val), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(val), i); } splay_tree_dtor(t); } void test_splay_tree_insert_or_assign() { splay_tree_t *t = NULL; pair_splay_tree_iter_bool_t ret = CDC_INIT_STRUCT; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctor(&t, &info), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_insert_or_assign(t, a.first, a.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 1); CU_ASSERT_EQUAL(splay_tree_iter_value(&ret.first), a.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(splay_tree_insert_or_assign(t, a.first, b.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 1); CU_ASSERT_EQUAL(splay_tree_get(t, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, b.second); CU_ASSERT_EQUAL(splay_tree_iter_value(&ret.first), b.second); CU_ASSERT(!ret.second); CU_ASSERT_EQUAL(splay_tree_insert_or_assign(t, c.first, c.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 2); CU_ASSERT_EQUAL(splay_tree_iter_value(&ret.first), c.second); CU_ASSERT(ret.second); CU_ASSERT_EQUAL(splay_tree_insert_or_assign(t, c.first, d.second, &ret), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 2); CU_ASSERT_EQUAL(splay_tree_get(t, c.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, d.second); CU_ASSERT_EQUAL(splay_tree_iter_value(&ret.first), d.second); CU_ASSERT(!ret.second); splay_tree_dtor(t); } void test_splay_tree_erase() { splay_tree_t *t = NULL; void *value = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 8); CU_ASSERT(splay_tree_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, a.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, a.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(splay_tree_key_int_eq(t, 7, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, h.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, h.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 6); CU_ASSERT(splay_tree_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, h.first), 0); CU_ASSERT_EQUAL(splay_tree_size(t), 6); CU_ASSERT(splay_tree_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, b.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, b.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 5); CU_ASSERT(splay_tree_key_int_eq(t, 5, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, c.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, c.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 4); CU_ASSERT(splay_tree_key_int_eq(t, 4, &d, &g, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, d.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, d.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 3); CU_ASSERT(splay_tree_key_int_eq(t, 3, &g, &e, &f)); CU_ASSERT_EQUAL(splay_tree_erase(t, f.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, f.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 2); CU_ASSERT(splay_tree_key_int_eq(t, 2, &g, &e)); CU_ASSERT_EQUAL(splay_tree_erase(t, e.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, e.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(splay_tree_size(t), 1); CU_ASSERT(splay_tree_key_int_eq(t, 1, &g)); CU_ASSERT_EQUAL(splay_tree_erase(t, g.first), 1); CU_ASSERT_EQUAL(splay_tree_get(t, g.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(splay_tree_empty(t)); splay_tree_dtor(t); } void test_splay_tree_iterators() { splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; CU_ASSERT_EQUAL(splay_tree_ctorl(&t, &info, &a, &b, &c, &d, &e, &f, &g, &h, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(splay_tree_size(t), 8); splay_tree_iter_t it1 = CDC_INIT_STRUCT; splay_tree_iter_t it2 = CDC_INIT_STRUCT; pair_t *arr[] = {&a, &b, &c, &d, &e, &f, &g, &h}; size_t i = 0; splay_tree_begin(t, &it1); splay_tree_end(t, &it2); for (; !splay_tree_iter_is_eq(&it1, &it2); splay_tree_iter_next(&it1)) { CU_ASSERT_EQUAL(splay_tree_iter_key(&it1), arr[i]->first) ++i; } CU_ASSERT_EQUAL(splay_tree_size(t), i); i = splay_tree_size(t) - 1; splay_tree_end(t, &it1); splay_tree_iter_prev(&it1); splay_tree_begin(t, &it2); for (; !splay_tree_iter_is_eq(&it1, &it2); splay_tree_iter_prev(&it1)) { CU_ASSERT_EQUAL(splay_tree_iter_key(&it1), arr[i]->first) --i; } CU_ASSERT_EQUAL(i, 0); splay_tree_begin(t, &it1); while (splay_tree_iter_has_next(&it1)) { CU_ASSERT_EQUAL(splay_tree_iter_key(&it1), arr[i]->first) ++i; splay_tree_iter_next(&it1); } CU_ASSERT_EQUAL(splay_tree_size(t), i); i = splay_tree_size(t) - 1; splay_tree_end(t, &it1); splay_tree_iter_prev(&it1); while (splay_tree_iter_has_prev(&it1)) { CU_ASSERT_EQUAL(splay_tree_iter_key(&it1), arr[i]->first); --i; splay_tree_iter_prev(&it1); } CU_ASSERT_EQUAL(i, 0); splay_tree_dtor(t); } void test_splay_tree_swap() { } void test_splay_tree_height() { size_t count = 100000; splay_tree_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.cmp = lt; splay_tree_ctor(&t, &info); for (size_t i = 0; i < count; ++i) { int val = rand(); if (splay_tree_insert(t, CDC_FROM_INT(val), NULL, NULL) != CDC_STATUS_OK) { CU_ASSERT(true); } } double experimental_height = cdc_tree_height(t->root); printf("\nExperimental splay tree heigth: %f, tree size: %zu\n", experimental_height, count); splay_tree_dtor(t); }
maksimandrianov/cdstructures
src/hash-table.c
<reponame>maksimandrianov/cdstructures<filename>src/hash-table.c // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/hash-table.h" #include "cdcontainers/data-info.h" #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define HASH_TABLE_MIN_CAPACITY 8 // must be pow 2 #define HASH_TABLE_COPACITY_SHIFT 1 #define HASH_TABLE_LOAD_FACTOR 0.7f static hash_table_entry_t *new_node(void *key, void *value, size_t hash) { hash_table_entry_t *new_entry = (hash_table_entry_t *)malloc(sizeof(hash_table_entry_t)); if (!new_entry) { return NULL; } new_entry->next = NULL; new_entry->value = value; new_entry->key = key; new_entry->hash = hash; return new_entry; } static void free_entry(hash_table_t *t, hash_table_entry_t *entry) { if (CDC_HAS_DFREE(t->dinfo)) { pair_t pair = {entry->key, entry->value}; t->dinfo->dfree(&pair); } free(entry); } static void free_entries(hash_table_t *t) { hash_table_entry_t *curr = t->buckets[0]->next; while (curr) { hash_table_entry_t *next = curr->next; free_entry(t, curr); curr = next; } } static void free_all_entries(hash_table_t *t) { free_entries(t); // free nil entry free(t->buckets[0]); } static bool should_rehash(hash_table_t *t) { return ((double)t->size / (double)t->bcount) >= t->load_factor; } static stat_t rehash(hash_table_t *t) { return hash_table_rehash(t, t->bcount << HASH_TABLE_COPACITY_SHIFT); } static size_t get_bucket(size_t hash, size_t count) { return hash & (count - 1); } static hash_table_entry_t *find_entry_by_bucket(hash_table_t *t, void *key, size_t bucket) { hash_table_entry_t *entry = t->buckets[bucket]; if (entry == NULL) { return NULL; } while (entry->next) { if (t->dinfo->eq(key, entry->next->key)) { return entry; } if (bucket != get_bucket(entry->next->hash, t->bcount)) { return NULL; } entry = entry->next; } return NULL; } static hash_table_entry_t *find_entry(hash_table_t *t, void *key) { size_t bucket = key ? get_bucket(t->dinfo->hash(key), t->bcount) : 0; return find_entry_by_bucket(t, key, bucket); } static hash_table_entry_t *add_entry(hash_table_t *t, hash_table_entry_t *new_entry) { size_t bucket = new_entry->key ? get_bucket(new_entry->hash, t->bcount) : 0; hash_table_entry_t *entry = t->buckets[bucket]; hash_table_entry_t *prev_entry = NULL; if (entry == NULL) { t->buckets[bucket] = t->tail; prev_entry = t->tail; t->tail->next = new_entry; t->tail = new_entry; } else { if (entry->next) { size_t next_bucket = get_bucket(entry->next->hash, t->bcount); if (next_bucket != bucket) { t->buckets[next_bucket] = new_entry; } prev_entry = entry; hash_table_entry_t *next = entry->next; entry->next = new_entry; new_entry->next = next; } else { prev_entry = t->tail; t->tail->next = new_entry; t->tail = new_entry; } } return prev_entry; } static stat_t make_and_insert_unique(hash_table_t *t, void *key, void *value, hash_table_entry_t **ret) { if (should_rehash(t)) { stat_t stat = rehash(t); if (stat != CDC_STATUS_OK) { return stat; } } hash_table_entry_t *entry = new_node(key, value, t->dinfo->hash(key)); if (!entry) { return CDC_STATUS_BAD_ALLOC; } *ret = add_entry(t, entry); ++t->size; return CDC_STATUS_OK; } static hash_table_entry_t *erase_entry(hash_table_t *t, hash_table_entry_t *entry, size_t bucket) { assert(entry != NULL); assert(entry->next != NULL); hash_table_entry_t *next = entry->next->next; size_t e_hash = get_bucket(entry->hash, t->bcount); size_t en_hash = get_bucket(entry->next->hash, t->bcount); free_entry(t, entry->next); if (next != NULL) { size_t n_hash = get_bucket(next->hash, t->bcount); if (e_hash != en_hash && en_hash != n_hash) { entry->next = next; if (entry == t->buckets[0]) { t->buckets[bucket] = t->buckets[0]; } else { t->buckets[bucket] = NULL; } bucket = get_bucket(next->hash, t->bcount); t->buckets[bucket] = entry; } else if (en_hash == n_hash) { entry->next = next; } else { entry->next = next; bucket = get_bucket(next->hash, t->bcount); t->buckets[bucket] = entry; } } else { if (e_hash != en_hash) { t->buckets[bucket] = NULL; } entry->next = NULL; t->tail = entry; } --t->size; return next; } static hash_table_entry_t **transfer(hash_table_t *t, hash_table_entry_t **buckets, size_t count) { hash_table_entry_t *entry = t->buckets[0]->next; hash_table_entry_t **old_buffer = t->buckets; // Set a new buffer and a new tail. t->buckets[0]->next = NULL; buckets[0] = t->buckets[0]; t->buckets = buckets; t->tail = buckets[0]; t->bcount = count; hash_table_entry_t *next_entry = NULL; while (entry) { next_entry = entry->next; entry->next = NULL; add_entry(t, entry); entry = next_entry; } return old_buffer; } static stat_t reallocate(hash_table_t *t, size_t count) { if (count < HASH_TABLE_MIN_CAPACITY) { if (t->bcount > HASH_TABLE_MIN_CAPACITY) { count = HASH_TABLE_MIN_CAPACITY; } else { return CDC_STATUS_OK; } } hash_table_entry_t **new_buckets = (hash_table_entry_t **)calloc(count * sizeof(void *), 1); if (!new_buckets) { return CDC_STATUS_BAD_ALLOC; } if (t->buckets) { hash_table_entry_t **old_buffer = transfer(t, new_buckets, count); free(old_buffer); } else { hash_table_entry_t *nil = (hash_table_entry_t *)calloc(sizeof(hash_table_entry_t), 1); if (!nil) { free(new_buckets); return CDC_STATUS_BAD_ALLOC; } t->buckets = new_buckets; t->buckets[0] = nil; t->tail = nil; t->bcount = count; } return CDC_STATUS_OK; } static stat_t init_varg(hash_table_t *t, va_list args) { pair_t *pair = NULL; while ((pair = va_arg(args, pair_t *)) != CDC_END) { stat_t stat = hash_table_insert(t, pair->first, pair->second, NULL, NULL); if (stat != CDC_STATUS_OK) { return stat; } } return CDC_STATUS_OK; } stat_t hash_table_ctor1(hash_table_t **t, data_info_t *info, double load_factor) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); assert(load_factor > 0); hash_table_t *tmp = (hash_table_t *)calloc(sizeof(hash_table_t), 1); if (!tmp) { return CDC_STATUS_BAD_ALLOC; } tmp->load_factor = load_factor; stat_t stat = CDC_STATUS_OK; if (info && !(tmp->dinfo = di_shared_ctorc(info))) { stat = CDC_STATUS_BAD_ALLOC; goto free_hash_table; } stat = reallocate(tmp, HASH_TABLE_MIN_CAPACITY); if (stat != CDC_STATUS_OK) { goto free_di; } *t = tmp; return stat; free_di: di_shared_dtor(tmp->dinfo); free_hash_table: free(tmp); return stat; } stat_t hash_table_ctorl1(hash_table_t **t, data_info_t *info, double load_factor, ...) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); assert(load_factor > 0); va_list args; va_start(args, load_factor); stat_t stat = cdc_hash_table_ctorv1(t, info, load_factor, args); va_end(args); return stat; } stat_t hash_table_ctorv1(hash_table_t **t, data_info_t *info, double load_factor, va_list args) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); assert(load_factor > 0); stat_t stat = hash_table_ctor1(t, info, load_factor); if (stat != CDC_STATUS_OK) { return stat; } return init_varg(*t, args); } stat_t hash_table_ctor(hash_table_t **t, data_info_t *info) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); return hash_table_ctor1(t, info, HASH_TABLE_LOAD_FACTOR); } stat_t hash_table_ctorl(hash_table_t **t, data_info_t *info, ...) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); va_list args; va_start(args, info); stat_t stat = hash_table_ctorv(t, info, args); va_end(args); return stat; } stat_t hash_table_ctorv(hash_table_t **t, data_info_t *info, va_list args) { assert(t != NULL); assert(CDC_HAS_HASH(info)); assert(CDC_HAS_EQ(info)); return hash_table_ctorv1(t, info, HASH_TABLE_LOAD_FACTOR, args); } void hash_table_dtor(hash_table_t *t) { assert(t != NULL); free_all_entries(t); free(t->buckets); di_shared_dtor(t->dinfo); free(t); } stat_t hash_table_get(hash_table_t *t, void *key, void **value) { assert(t != NULL); hash_table_entry_t *entry = find_entry(t, key); if (!entry) { return CDC_STATUS_NOT_FOUND; } *value = entry->next->value; return CDC_STATUS_OK; } size_t hash_table_count(hash_table_t *t, void *key) { assert(t != NULL); return (size_t)(find_entry(t, key) != NULL); } void hash_table_find(hash_table_t *t, void *key, hash_table_iter_t *it) { assert(t != NULL); assert(it != NULL); hash_table_entry_t *entry = find_entry(t, key); it->container = t; it->current = entry ? entry->next : NULL; } void hash_table_clear(hash_table_t *t) { assert(t != NULL); free_entries(t); t->buckets[0]->next = NULL; t->tail = t->buckets[0]; t->size = 0; } stat_t hash_table_insert(hash_table_t *t, void *key, void *value, hash_table_iter_t *it, bool *inserted) { assert(t != NULL); hash_table_entry_t *entry = find_entry(t, key); bool finded = entry; if (!finded) { stat_t stat = make_and_insert_unique(t, key, value, &entry); if (stat != CDC_STATUS_OK) { return stat; } } if (it) { it->container = t; it->current = entry->next; } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } stat_t hash_table_insert_or_assign(hash_table_t *t, void *key, void *value, hash_table_iter_t *it, bool *inserted) { assert(t != NULL); hash_table_entry_t *entry = find_entry(t, key); bool finded = entry; if (!finded) { stat_t stat = make_and_insert_unique(t, key, value, &entry); if (stat != CDC_STATUS_OK) { return stat; } } else { entry->next->value = value; } if (it) { it->container = t; it->current = entry->next; } if (inserted) { *inserted = !finded; } return CDC_STATUS_OK; } size_t hash_table_erase(hash_table_t *t, void *key) { assert(t != NULL); size_t bucket = key ? get_bucket(t->dinfo->hash(key), t->bcount) : 0; hash_table_entry_t *entry = find_entry_by_bucket(t, key, bucket); if (!entry) { return 0; } erase_entry(t, entry, bucket); return 1; } void hash_table_swap(hash_table_t *a, hash_table_t *b) { assert(a != NULL); assert(b != NULL); CDC_SWAP(hash_table_entry_t *, a->tail, b->tail); CDC_SWAP(hash_table_entry_t **, a->buckets, b->buckets); CDC_SWAP(size_t, a->bcount, b->bcount); CDC_SWAP(double, a->load_factor, b->load_factor); CDC_SWAP(size_t, a->size, b->size); CDC_SWAP(data_info_t *, a->dinfo, b->dinfo); } stat_t hash_table_rehash(hash_table_t *t, size_t count) { assert(t != NULL); if (count <= t->bcount) { return CDC_STATUS_OK; } count = cdc_up_to_pow2(count); assert(count != 0); return reallocate(t, count); } stat_t hash_table_reserve(hash_table_t *t, size_t count) { assert(t != NULL); return hash_table_rehash(t, (size_t)((double)count / t->load_factor) + 1); }
maksimandrianov/cdstructures
include/cdcontainers/pairing-heap.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_pairing_heap is a struct and functions that provide a * pairing heap */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_PAIRING_HEAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_PAIRING_HEAP_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_pairing_heap_node struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_pairing_heap_node { struct cdc_pairing_heap_node *parent; struct cdc_pairing_heap_node *child; struct cdc_pairing_heap_node *sibling; void *key; }; /** * @brief The cdc_pairing_heap struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_pairing_heap { struct cdc_pairing_heap_node *root; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_pairing_heap_iter struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_pairing_heap_iter { struct cdc_pairing_heap *container; struct cdc_pairing_heap_node *current; }; /** * @brief Constructs an empty pairing heap. * @param h - cdc_pairing_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_pairing_heap_ctor(struct cdc_pairing_heap **h, struct cdc_data_info *info); /** * @brief Constructs a pairing heap, initialized by an arbitrary number of * pointers. The last item must be NULL. * @param h - cdc_pairing_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_pairing_heap_ctorl(struct cdc_pairing_heap **h, struct cdc_data_info *info, ...); /** * @brief Constructs a pairing heap, initialized by args. The last item must be * NULL. * @param h - cdc_pairing_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_pairing_heap_ctorv(struct cdc_pairing_heap **h, struct cdc_data_info *info, va_list args); /** * @brief Destroys the pairing heap. * @param h - cdc_pairing_heap */ void cdc_pairing_heap_dtor(struct cdc_pairing_heap *h); // Element access /** * @brief Returns a pointer to the pairing heap's top item. This function * assumes that the pairing heap isn't empty. * @param h - cdc_pairing_heap * @return top item */ static inline void *cdc_pairing_heap_top(struct cdc_pairing_heap *h) { assert(h != NULL); return h->root->key; } // Capacity /** * @brief Returns the number of items in the pairing heap. * @param h - cdc_pairing_heap * @return size */ static inline size_t cdc_pairing_heap_size(struct cdc_pairing_heap *h) { assert(h != NULL); return h->size; } /** * @brief Returns true if the pairing heap has size 0; otherwise returns false. * @param h - cdc_pairing_heap * @return true if the pairing heap has size 0; otherwise returns false */ static inline bool cdc_pairing_heap_empty(struct cdc_pairing_heap *h) { assert(h != NULL); return h->size == 0; } // Modifiers /** * @brief Extracts the top item from the pairing heap. This function assumes * that the pairing heap isn't empty. * @param h - cdc_pairing_heap * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_pairing_heap_extract_top(struct cdc_pairing_heap *h); /** * @brief Inserts element key to the pairing heap. Write an iterator pointing * to a new element in the ret * @param h a cdc_pairing_heap * @param key * @param ret - pointer to iterator where an iterator will be written indicating * the inserted element * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_pairing_heap_riinsert(struct cdc_pairing_heap *h, void *key, struct cdc_pairing_heap_iter *ret); /** * @brief Inserts element key to the pairing heap. * @param h - cdc_pairing_heap * @param key * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_pairing_heap_insert(struct cdc_pairing_heap *h, void *key) { assert(h != NULL); return cdc_pairing_heap_riinsert(h, key, NULL); } /** * @brief Changes the item key on the pos position in the pairing heap. * @param h - cdc_pairing_heap * @param pos - iterator that indicates the item with key that you want to * change * @param key */ void cdc_pairing_heap_change_key(struct cdc_pairing_heap *h, struct cdc_pairing_heap_iter *pos, void *key); /** * @brief Removes all the elements from the pairing heap. * @param h - cdc_pairing_heap */ void cdc_pairing_heap_clear(struct cdc_pairing_heap *h); /** * @brief Swaps pairing heaps a and b. This operation is very fast and never * fails. * @param a - cdc_pairing_heap * @param b - cdc_pairing_heap */ void cdc_pairing_heap_swap(struct cdc_pairing_heap *a, struct cdc_pairing_heap *b); // Operations /** * @brief Merges two heaps. In the heap h will be the result of the merger, * and the heap other will remain empty. * @param h - cdc_pairing_heap * @param other - other cdc_pairing_heap */ void cdc_pairing_heap_merge(struct cdc_pairing_heap *h, struct cdc_pairing_heap *other); /** * @brief Checks the heap property. * @param h - cdc_pairing_heap * @return result of the check */ bool cdc_pairing_heap_is_heap(struct cdc_pairing_heap *h); // Iterators /** * @brief Returns a pointer to the key of current item. */ static inline void *cdc_pairing_heap_iter_data(struct cdc_pairing_heap_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns false if the iterator it1 equal to the iterator it2, * otherwise returns false */ static inline bool cdc_pairing_heap_iter_is_eq(struct cdc_pairing_heap_iter *it1, struct cdc_pairing_heap_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->current == it2->current; } // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_pairing_heap_node pairing_heap_node_t; typedef struct cdc_pairing_heap pairing_heap_t; typedef struct cdc_pairing_heap_iter pairing_heap_iter_t; #define pairing_heap_ctor(...) cdc_pairing_heap_ctor(__VA_ARGS__) #define pairing_heap_ctorl(...) cdc_pairing_heap_ctorl(__VA_ARGS__) #define pairing_heap_ctorv(...) cdc_pairing_heap_ctorv(__VA_ARGS__) #define pairing_heap_dtor(...) cdc_pairing_heap_dtor(__VA_ARGS__) // Element access #define pairing_heap_top(...) cdc_pairing_heap_top(__VA_ARGS__) // Capacity #define pairing_heap_empty(...) cdc_pairing_heap_empty(__VA_ARGS__) #define pairing_heap_size(...) cdc_pairing_heap_size(__VA_ARGS__) // Modifiers #define pairing_heap_extract_top(...) cdc_pairing_heap_extract_top(__VA_ARGS__) #define pairing_heap_riinsert(...) cdc_pairing_heap_riinsert(__VA_ARGS__) #define pairing_heap_insert(...) cdc_pairing_heap_insert(__VA_ARGS__) #define pairing_heap_change_key(...) cdc_pairing_heap_change_key(__VA_ARGS__) #define pairing_heap_clear(...) cdc_pairing_heap_clear(__VA_ARGS__) #define pairing_heap_swap(...) cdc_pairing_heap_swap(__VA_ARGS__) // Operations #define pairing_heap_merge(...) cdc_pairing_heap_merge(__VA_ARGS__) #define pairing_heap_is_heap(...) cdc_pairing_heap_is_heap(__VA_ARGS__) // Iterators #define pairing_heap_iter_data(...) cdc_pairing_heap_iter_data(__VA_ARGS__) #define pairing_heap_iter_is_eq(...) cdc_pairing_heap_iter_is_eq(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_PAIRING_HEAP_H
maksimandrianov/cdstructures
include/cdcontainers/data-info.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef CDCONTAINERS_SRC_DATA_INFO_H #define CDCONTAINERS_SRC_DATA_INFO_H #include <cdcontainers/common.h> struct cdc_data_info *cdc_di_shared_ctorc(struct cdc_data_info *other); void cdc_di_shared_dtor(struct cdc_data_info *info); #define CDC_HAS_DFREE(dinfo) (dinfo && dinfo->dfree) #define CDC_HAS_CMP(dinfo) (dinfo && dinfo->cmp) #define CDC_HAS_EQ(dinfo) (dinfo && dinfo->eq) #define CDC_HAS_HASH(dinfo) (dinfo && dinfo->hash) #define CDC_HAS_CP(dinfo) (dinfo && dinfo->cp) #define CDC_HAS_SIZE(dinfo) (dinfo && dinfo->size) static inline int cdc_eq(int (*pred)(const void *, const void *), const void *l, const void *r) { return !(pred(l, r) || pred(r, l)); } static inline int cdc_not_eq(int (*pred)(const void *, const void *), const void *l, const void *r) { return pred(l, r) || pred(r, l); } static inline int cdc_gt(int (*pred)(const void *, const void *), const void *l, const void *r) { return pred(r, l); } static inline int cdc_gte(int (*pred)(const void *, const void *), const void *l, const void *r) { return !pred(l, r); } static inline int cdc_lte(int (*pred)(const void *, const void *), const void *l, const void *r) { return !pred(r, l); } // Short names #ifdef CDC_USE_SHORT_NAMES #define di_shared_ctorc(...) cdc_di_shared_ctorc(__VA_ARGS__) #define di_shared_dtor(...) cdc_di_shared_dtor(__VA_ARGS__) #endif #endif // CDCONTAINERS_SRC_DATA_INFO_Hs
maksimandrianov/cdstructures
include/cdcontainers/hash-table.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_hash_table is a struct and functions that provide a hash table. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_TABLE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_TABLE_H #include <cdcontainers/common.h> #include <cdcontainers/hash.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @defgroup cdc_hash_table * @brief The cdc_hash_table is a struct and functions that provide a hash table. * @{ */ /** * @brief The cdc_hash_table_entry struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_hash_table_entry { struct cdc_hash_table_entry *next; void *key; void *value; size_t hash; }; /** * @brief The cdc_hash_table is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_hash_table { struct cdc_hash_table_entry *tail; struct cdc_hash_table_entry **buckets; size_t bcount; double load_factor; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_hash_table_iter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_hash_table_iter { struct cdc_hash_table *container; struct cdc_hash_table_entry *current; }; // Base /** * @defgroup cdc_hash_table_base Base * @{ */ /** * @brief Constructs an empty hash table. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_ctor(struct cdc_hash_table **t, struct cdc_data_info *info); /** * @brief Constructs a hash table, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_hash_table *table = NULL; * cdc_pair value1 = {CDC_FROM_INT(1), CDC_FROM_INT(2)}; * cdc_pair value2 = {CDC_FROM_INT(3), CDC_FROM_INT(4)}; * ... * if (cdc_hash_table_ctorl(&table, info, &value1, &value2, CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_hash_table_ctorl(struct cdc_hash_table **t, struct cdc_data_info *info, ...); /** * @brief Constructs a hash table, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_ctorv(struct cdc_hash_table **t, struct cdc_data_info *info, va_list args); /** * @brief Constructs an empty hash table. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @param[in] load_factor - maximum load factor * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_ctor1(struct cdc_hash_table **t, struct cdc_data_info *info, double load_factor); /** * @brief Constructs a hash table, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @param[in] load_factor - maximum load factor * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_ctorl1(struct cdc_hash_table **t, struct cdc_data_info *info, double load_factor, ...); /** * @brief Constructs a hash table, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_hash_table * @param[in] info - cdc_data_info * @param[in] load_factor - maximum load factor * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_ctorv1(struct cdc_hash_table **t, struct cdc_data_info *info, double load_factor, va_list args); /** * @brief Destroys the hash table. * @param[in] t - cdc_hash_table */ void cdc_hash_table_dtor(struct cdc_hash_table *t); /** @} */ // Lookup /** * @defgroup cdc_hash_table_lookup Lookup * @{ */ /** * @brief Returns a value that is mapped to a key. If the key does * not exist, then NULL will return. * @param[in] t - cdc_hash_table * @param[in] key - key of the element to find * @param[out] value - pinter to the value that is mapped to a key. * @return CDC_STATUS_OK if the key is found, CDC_STATUS_NOT_FOUND otherwise. */ enum cdc_stat cdc_hash_table_get(struct cdc_hash_table *t, void *key, void **value); /** * @brief Returns the number of elements with key that compares equal to the * specified argument key, which is either 1 or 0 since this container does not * allow duplicates. * @param[in] t - cdc_hash_table * @param[in] key - key value of the elements to count * @return number of elements with key key, that is either 1 or 0. */ size_t cdc_hash_table_count(struct cdc_hash_table *t, void *key); /** * @brief Finds an element with key equivalent to key. * @param[in] t - cdc_hash_table * @param[in] key - key value of the element to search for * @param[out] it - pointer will be recorded iterator to an element with key * equivalent to key. If no such element is found, past-the-end iterator is * returned. */ void cdc_hash_table_find(struct cdc_hash_table *t, void *key, struct cdc_hash_table_iter *it); /** @} */ // Capacity /** * @defgroup cdc_hash_table_capacity Capacity * @{ */ /** * @brief Returns the number of items in the hash_table. * @param[in] t - cdc_hash_table * @return the number of items in the hash_table. */ static inline size_t cdc_hash_table_size(struct cdc_hash_table *t) { assert(t != NULL); return t->size; } /** * @brief Checks if the hash table has no elements. * @param[in] t - cdc_hash_table * @return true if the hash table is empty, false otherwise. */ static inline bool cdc_hash_table_empty(struct cdc_hash_table *t) { assert(t != NULL); return t->size == 0; } /** @} */ // Modifiers /** * @defgroup cdc_hash_table_modifiers Modifiers * @{ */ /** * @brief Removes all the elements from the hash_table. * @param[in] t - cdc_hash_table */ void cdc_hash_table_clear(struct cdc_hash_table *t); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_hash_table * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair consisting of an iterator to the inserted element (or to * the element that prevented the insertion) and a bool denoting whether the * insertion took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_insert(struct cdc_hash_table *t, void *key, void *value, struct cdc_hash_table_iter *it, bool *inserted); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_hash_table * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair. The bool component is true if the insertion took place and * false if the assignment took place. The iterator component is pointing at the * element that was inserted or updated. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_insert_or_assign(struct cdc_hash_table *t, void *key, void *value, struct cdc_hash_table_iter *it, bool *inserted); /** * @brief Removes the element (if one exists) with the key equivalent to key. * @param[in] t - cdc_hash_table * @param[in] key - key value of the elements to remove * @return number of elements removed. */ size_t cdc_hash_table_erase(struct cdc_hash_table *t, void *key); /** * @brief Swaps hash_tables a and b. This operation is very fast and never fails. * @param[in, out] a - cdc_hash_table * @param[in, out] b - cdc_hash_table */ void cdc_hash_table_swap(struct cdc_hash_table *a, struct cdc_hash_table *b); /** @} */ // Iterators /** * @defgroup cdc_hash_table_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param t[in] - cdc_hash_table * @param it[out] - cdc_hash_table_iter */ static inline void cdc_hash_table_begin(struct cdc_hash_table *t, struct cdc_hash_table_iter *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = t->buckets[0]->next; } /** * @brief Initializes the iterator to the end. * @param[in] t - cdc_hash_table * @param[out] it - cdc_hash_table_iter */ static inline void cdc_hash_table_end(struct cdc_hash_table *t, struct cdc_hash_table_iter *it) { assert(t != NULL); assert(it != NULL); it->container = t; it->current = NULL; } /** @} */ // Hash policy /** * @defgroup cdc_hash_table_hash_policy Hash policy * @{ */ /** * @brief Returns average number of elements per bucket. * @param[in] t - cdc_hash_table * @return average number of elements per bucket. */ static inline double cdc_hash_table_load_factor(struct cdc_hash_table *t) { assert(t != NULL); return (double)t->size / (double)t->bcount; } /** * @brief Returns current maximum load factor. * @param[in] t - cdc_hash_table * @return current maximum load factor. */ static inline double cdc_hash_table_max_load_factor(struct cdc_hash_table *t) { assert(t != NULL); return t->load_factor; } /** * @brief Sets the maximum load factor. * @param[in] t - cdc_hash_table * @param[in] load_factor - new maximum load factor */ static inline void cdc_hash_table_set_max_load_factor(struct cdc_hash_table *t, double load_factor) { assert(t != NULL); t->load_factor = load_factor; } /** * @brief Reserves at least the specified number of buckets. This regenerates * the hash table. * @param[in] t - cdc_hash_table * @param[in] count - new number of buckets * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_rehash(struct cdc_hash_table *t, size_t count); /** * @brief Reserves space for at least the specified number of elements. This * regenerates the hash table. * @param[in] t - cdc_hash_table * @param[in] count - new capacity of the container * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_hash_table_reserve(struct cdc_hash_table *t, size_t count); /** @} */ // Bucket interface /** * @defgroup cdc_hash_table_bucket_interface Bucket interface * @{ */ /** * @brief Returns the number of buckets. * @param[in] t - cdc_hash_table * @return returns the number of buckets. */ static inline size_t cdc_hash_table_bucket_count(struct cdc_hash_table *t) { assert(t != NULL); return t->bcount; } /** @} */ // Iterators /** * @defgroup cdc_hash_table_iter * @brief The cdc_hash_table_iter is a struct and functions that provide a hash table iterator. * @{ */ /** * @brief Advances the iterator to the next element in the hash table. * @param[in] it - iterator */ static inline void cdc_hash_table_iter_next(struct cdc_hash_table_iter *it) { assert(it != NULL); it->current = it->current->next; } /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_hash_table_iter_has_next(struct cdc_hash_table_iter *it) { assert(it != NULL); return it->current != NULL; } /** * @brief Returns an item's key. * @param[in] it - iterator * @return the item's key. */ static inline void *cdc_hash_table_iter_key(struct cdc_hash_table_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns an item's value. * @param[in] it - iterator * @return the item's value. */ static inline void *cdc_hash_table_iter_value(struct cdc_hash_table_iter *it) { assert(it != NULL); return it->current->value; } /** * @brief Returns a pair, where first - key, second - value. * @param[in] it - iterator * @return pair, where first - key, second - value. */ static inline struct cdc_pair cdc_hash_table_iter_key_value(struct cdc_hash_table_iter *it) { assert(it != NULL); struct cdc_pair pair = {it->current->key, it->current->value}; return pair; } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_hash_table_iter_is_eq(struct cdc_hash_table_iter *it1, struct cdc_hash_table_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->current == it2->current; } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_hash_table_entry hash_table_entry_t; typedef struct cdc_hash_table hash_table_t; typedef struct cdc_hash_table_iter hash_table_iter_t; typedef struct cdc_pair_hash_table_iter pair_hash_table_iter_t; typedef struct cdc_pair_hash_table_iter_bool pair_hash_table_iter_bool_t; // Base #define hash_table_ctor(...) cdc_hash_table_ctor(__VA_ARGS__) #define hash_table_ctorl(...) cdc_hash_table_ctorl(__VA_ARGS__) #define hash_table_ctorv(...) cdc_hash_table_ctorv(__VA_ARGS__) #define hash_table_ctor1(...) cdc_hash_table_ctor1(__VA_ARGS__) #define hash_table_ctorl1(...) cdc_hash_table_ctorl1(__VA_ARGS__) #define hash_table_ctorv1(...) cdc_hash_table_ctorv1(__VA_ARGS__) #define hash_table_dtor(...) cdc_hash_table_dtor(__VA_ARGS__) // Lookup #define hash_table_get(...) cdc_hash_table_get(__VA_ARGS__) #define hash_table_count(...) cdc_hash_table_count(__VA_ARGS__) #define hash_table_find(...) cdc_hash_table_find(__VA_ARGS__) // Capacity #define hash_table_size(...) cdc_hash_table_size(__VA_ARGS__) #define hash_table_empty(...) cdc_hash_table_empty(__VA_ARGS__) // Modifiers #define hash_table_clear(...) cdc_hash_table_clear(__VA_ARGS__) #define hash_table_insert(...) cdc_hash_table_insert(__VA_ARGS__) #define hash_table_insert_or_assign(...) cdc_hash_table_insert_or_assign(__VA_ARGS__) #define hash_table_erase(...) cdc_hash_table_erase(__VA_ARGS__) #define hash_table_swap(...) cdc_hash_table_swap(__VA_ARGS__) // Iterators #define hash_table_begin(...) cdc_hash_table_begin(__VA_ARGS__) #define hash_table_end(...) cdc_hash_table_end(__VA_ARGS__) // Hash policy #define hash_table_load_factor(...) cdc_hash_table_load_factor(__VA_ARGS__) #define hash_table_max_load_factor(...) cdc_hash_table_max_load_factor(__VA_ARGS__) #define hash_table_set_max_load_factor(...) cdc_hash_table_set_max_load_factor(__VA_ARGS__) #define hash_table_rehash(...) cdc_hash_table_rehash(__VA_ARGS__) #define hash_table_reserve(...) cdc_hash_table_reserve(__VA_ARGS__) // Bucket interface #define hash_table_bucket_count(...) cdc_hash_table_bucket_count(__VA_ARGS__) // Iterators #define hash_table_iter_next(...) cdc_hash_table_iter_next(__VA_ARGS__) #define hash_table_iter_has_next(...) cdc_hash_table_iter_has_next(__VA_ARGS__) #define hash_table_iter_key(...) cdc_hash_table_iter_key(__VA_ARGS__) #define hash_table_iter_value(...) cdc_hash_table_iter_value(__VA_ARGS__) #define hash_table_iter_key_value(...) cdc_hash_table_iter_key_value(__VA_ARGS__) #define hash_table_iter_is_eq(...) cdc_hash_table_iter_is_eq(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_HASH_TABLE_H
maksimandrianov/cdstructures
tests/test-array.c
<reponame>maksimandrianov/cdstructures<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/array.h" #include "cdcontainers/casts.h" #include "cdcontainers/common.h" #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> static bool array_range_int_eq(array_t *v, size_t count, ...) { va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { int elem = va_arg(args, int); if (elem != CDC_TO_INT(array_get(v, i))) { return false; } } return true; } void test_array_ctor() { array_t *v = NULL; CU_ASSERT_EQUAL(array_ctor(&v, NULL), CDC_STATUS_OK); CU_ASSERT(array_empty(v)); array_dtor(v); } void test_array_ctorl() { array_t *v = NULL; int a = 0, b = 1, c = 2, d = 3; size_t count_elements = 4; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_size(v), count_elements); CU_ASSERT(array_range_int_eq(v, count_elements, a, b, c, d)); array_dtor(v); } void test_array_reserve() { array_t *v = NULL; size_t count_reserved = 10; CU_ASSERT_EQUAL(array_ctor(&v, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_reserve(v, count_reserved), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_capacity(v), count_reserved); CU_ASSERT_EQUAL(array_reserve(v, count_reserved - 1), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_capacity(v), count_reserved); array_dtor(v); } void test_array_data() { array_t *v = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT((array_data(v)[0])), a); CU_ASSERT_EQUAL(CDC_TO_INT((array_data(v)[1])), b); CU_ASSERT_EQUAL(CDC_TO_INT((array_data(v)[2])), c); CU_ASSERT_EQUAL(CDC_TO_INT((array_data(v)[3])), d); array_dtor(v); } void test_array_get() { array_t *v = NULL; int a = 0, b = 1; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(array_get(v, 0)), a); CU_ASSERT_EQUAL(CDC_TO_INT(array_get(v, 1)), b); array_dtor(v); } void test_array_at() { array_t *v = NULL; int a = 0, b = 1, c = 2; void *elem = NULL; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_at(v, 0, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); CU_ASSERT_EQUAL(array_at(v, 1, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); CU_ASSERT_EQUAL(array_at(v, 2, &elem), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); size_t index = array_size(v) + 1; CU_ASSERT_EQUAL(array_at(v, index, &elem), CDC_STATUS_OUT_OF_RANGE); array_dtor(v); } void test_array_set() { array_t *v = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); array_set(v, 0, CDC_FROM_INT(b)); CU_ASSERT(array_range_int_eq(v, 2, b, b)); array_set(v, 1, CDC_FROM_INT(a)); CU_ASSERT(array_range_int_eq(v, 2, b, a)); array_dtor(v); } void test_array_front() { array_t *v = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(array_front(v)), a); array_dtor(v); } void test_array_back() { array_t *v = NULL; int a = 1, b = 2; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(array_back(v)), b); array_dtor(v); } void test_array_insert() { array_t *v = NULL; int a = 1, b = 2; int i1 = 3, i2 = 4, i3 = 5; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_insert(v, 0, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_size(v), 3); CU_ASSERT(array_range_int_eq(v, 3, i1, a, b)); CU_ASSERT_EQUAL(array_insert(v, array_size(v), CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_size(v), 4); CU_ASSERT(array_range_int_eq(v, 4, i1, a, b, i2)); CU_ASSERT_EQUAL(array_insert(v, 2, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_size(v), 5); CU_ASSERT(array_range_int_eq(v, 5, i1, a, i3, b, i2)); array_dtor(v); } void test_array_erase() { array_t *v = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); array_erase(v, 2); CU_ASSERT_EQUAL(array_size(v), 3); CU_ASSERT(array_range_int_eq(v, 3, a, b, d)); array_erase(v, 0); CU_ASSERT_EQUAL(array_size(v), 2); CU_ASSERT(array_range_int_eq(v, 2, b, d)); array_erase(v, array_size(v) - 1); CU_ASSERT_EQUAL(array_size(v), 1); CU_ASSERT(array_range_int_eq(v, 1, b)); array_dtor(v); } void test_array_clear() { array_t *v = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); array_clear(v); CU_ASSERT(array_empty(v)); array_dtor(v); } void test_array_push_back() { array_t *v = NULL; int a = 0, b = 1, c = 2; CU_ASSERT_EQUAL(array_ctor(&v, NULL), CDC_STATUS_OK); array_push_back(v, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(array_size(v), 1); CU_ASSERT(array_range_int_eq(v, 1, a)); array_push_back(v, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(array_size(v), 2); CU_ASSERT(array_range_int_eq(v, 1, a, b)); array_push_back(v, CDC_FROM_INT(c)); CU_ASSERT_EQUAL(array_size(v), 3); CU_ASSERT(array_range_int_eq(v, 3, a, b, c)); array_dtor(v); } void test_array_pop_back() { array_t *v = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = array_back(v); array_pop_back(v); CU_ASSERT_EQUAL(array_size(v), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); elem = array_back(v); array_pop_back(v); CU_ASSERT_EQUAL(array_size(v), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = array_back(v); array_pop_back(v); CU_ASSERT_EQUAL(array_size(v), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = array_back(v); array_pop_back(v); CU_ASSERT(array_empty(v)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); array_dtor(v); } void test_array_swap() { array_t *v = NULL; array_t *w = NULL; int a = 0, b = 1, c = 2, d = 3; CU_ASSERT_EQUAL(array_ctorl(&v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(array_ctorl(&w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); array_swap(v, w); CU_ASSERT_EQUAL(array_size(v), 2); CU_ASSERT(array_range_int_eq(v, 2, a, d)); CU_ASSERT_EQUAL(array_size(w), 4); CU_ASSERT(array_range_int_eq(w, 4, a, b, c, d)); array_dtor(v); array_dtor(w); } void test_array_shrink_to_fit() { array_t *v = NULL; const int count = 100; CU_ASSERT_EQUAL(array_ctor(&v, NULL), CDC_STATUS_OK); for (int i = 0; i < count; ++i) { CU_ASSERT_EQUAL(array_push_back(v, CDC_FROM_INT(i)), CDC_STATUS_OK); } CU_ASSERT(array_capacity(v) > (size_t)count); array_shrink_to_fit(v); CU_ASSERT_EQUAL(array_capacity(v), count); array_dtor(v); }
maksimandrianov/cdstructures
include/cdcontainers/adapters/priority-queue.h
<reponame>maksimandrianov/cdstructures<filename>include/cdcontainers/adapters/priority-queue.h // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_priority_queue is a struct and functions that provide a * priority queue */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_PRIORITY_QUEUE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_PRIORITY_QUEUE_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <cdcontainers/tables/ipqueue.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_priority_queue struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_priority_queue { void *container; const struct cdc_priority_queue_table *table; }; /** * @brief Constructs an empty priority queue. * @param table - method table for a particular implementation * @param q - cdc_priority_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_priority_queue_ctor(const struct cdc_priority_queue_table *table, struct cdc_priority_queue **q, struct cdc_data_info *info); /** * @brief Constructs a priority queue, initialized by an arbitrary number of * pointers. The last item must be NULL. * @param table - method table for a particular implementation * @param q - cdc_priority_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_priority_queue_ctorl(const struct cdc_priority_queue_table *table, struct cdc_priority_queue **q, struct cdc_data_info *info, ...); /** * @brief Constructs a priority queue, initialized by args. * The last item must be NULL. * @param table - method table for a particular implementation * @param q - cdc_priority_queue * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_priority_queue_ctorv(const struct cdc_priority_queue_table *table, struct cdc_priority_queue **q, struct cdc_data_info *info, va_list args); /** * @brief Destroys the priority queue. * @param q - cdc_priority_queue */ void cdc_priority_queue_dtor(struct cdc_priority_queue *q); // Element access /** * @brief Returns a pointer to the priority queue's top item. This function * assumes that the priority queue isn't empty. * @param q - cdc_priority_queue * @return top item */ static inline void *cdc_priority_queue_top(struct cdc_priority_queue *q) { assert(q != NULL); return q->table->top(q->container); } // Capacity /** * @brief Returns true if the priority queue has size 0; otherwise returns * false. * @param q - cdc_priority_queue * @return true if the pairing heap has size 0; otherwise returns false */ static inline bool cdc_priority_queue_empty(struct cdc_priority_queue *q) { assert(q != NULL); return q->table->empty(q->container); } /** * @brief Returns the number of items in the priority queue. * @param q - cdc_priority_queue * @return size */ static inline size_t cdc_priority_queue_size(struct cdc_priority_queue *q) { assert(q != NULL); return q->table->size(q->container); } // Modifiers /** * @brief Adds element elem to the priority queue. * @param q - cdc_priority_queue * @param elem * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_priority_queue_push(struct cdc_priority_queue *q, void *elem) { assert(q != NULL); return q->table->push(q->container, elem); } /** * @brief Removes the top element. * @param q - cdc_priority_queue */ static inline void cdc_priority_queue_pop(struct cdc_priority_queue *q) { assert(q != NULL); q->table->pop(q->container); } /** * @brief Swaps priority queues a and b. This operation is very fast and never * fails. * @param a - cdc_priority_queue * @param b - cdc_priority_queue */ void cdc_priority_queue_swap(struct cdc_priority_queue *a, struct cdc_priority_queue *b); // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_priority_queue priority_queue_t; #define priority_queue_ctor(...) cdc_priority_queue_ctor(__VA_ARGS__) #define priority_queue_ctorl(...) cdc_priority_queue_ctorl(__VA_ARGS__) #define priority_queue_ctorv(...) cdc_priority_queue_ctorv(__VA_ARGS__) #define priority_queue_dtor(...) cdc_priority_queue_dtor(__VA_ARGS__) // Element access #define priority_queue_top(...) cdc_priority_queue_top(__VA_ARGS__) // Capacity #define priority_queue_empty(...) cdc_priority_queue_empty(__VA_ARGS__) #define priority_queue_size(...) cdc_priority_queue_size(__VA_ARGS__) // Modifiers #define priority_queue_push(...) cdc_priority_queue_push(__VA_ARGS__) #define priority_queue_pop(...) cdc_priority_queue_pop(__VA_ARGS__) #define priority_queue_swap(...) cdc_priority_queue_swap(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_PRIORITY_QUEUE_H
maksimandrianov/cdstructures
tests/test-main.c
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "cdcontainers/global.h" #include "test-common.h" #include <CUnit/Basic.h> int main(int argc, char** argv) { CDC_UNUSED(argc); CDC_UNUSED(argv); CU_pSuite p_suite = NULL; if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } p_suite = CU_add_suite("COMMON TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "ptr_float_cast", test_ptr_float_cast) == NULL || CU_add_test(p_suite, "ptr_double_cast", test_ptr_double_cast) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("ARRAY TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_array_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_array_ctorl) == NULL || CU_add_test(p_suite, "test_reserve", test_array_reserve) == NULL || CU_add_test(p_suite, "test_data", test_array_data) == NULL || CU_add_test(p_suite, "test_get", test_array_get) == NULL || CU_add_test(p_suite, "test_at", test_array_at) == NULL || CU_add_test(p_suite, "test_set", test_array_set) == NULL || CU_add_test(p_suite, "test_front", test_array_front) == NULL || CU_add_test(p_suite, "test_back", test_array_back) == NULL || CU_add_test(p_suite, "test_insert", test_array_insert) == NULL || CU_add_test(p_suite, "test_erase", test_array_erase) == NULL || CU_add_test(p_suite, "test_clear", test_array_clear) == NULL || CU_add_test(p_suite, "test_push_back", test_array_push_back) == NULL || CU_add_test(p_suite, "test_pop_back", test_array_pop_back) == NULL || CU_add_test(p_suite, "test_swap", test_array_swap) == NULL || CU_add_test(p_suite, "test_shrink_to_fit", test_array_shrink_to_fit) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("LIST TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_list_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_list_ctorl) == NULL || CU_add_test(p_suite, "test_push_back", test_list_push_back) == NULL || CU_add_test(p_suite, "test_push_front", test_list_push_front) == NULL || CU_add_test(p_suite, "test_at", test_list_at) == NULL || CU_add_test(p_suite, "test_front", test_list_front) == NULL || CU_add_test(p_suite, "test_back", test_list_back) == NULL || CU_add_test(p_suite, "test_pop_back", test_list_pop_back) == NULL || CU_add_test(p_suite, "test_pop_front", test_list_pop_front) == NULL || CU_add_test(p_suite, "test_swap", test_list_swap) == NULL || CU_add_test(p_suite, "test_insert", test_list_insert) == NULL || CU_add_test(p_suite, "test_erase", test_list_erase) == NULL || CU_add_test(p_suite, "test_ierase", test_list_ierase) == NULL || CU_add_test(p_suite, "test_clear", test_list_clear) == NULL || CU_add_test(p_suite, "test_iterators", test_list_iterators) == NULL || CU_add_test(p_suite, "test_reverse_iterators", test_list_reverse_iterators) == NULL || CU_add_test(p_suite, "test_splice", test_list_splice) == NULL || CU_add_test(p_suite, "test_ssplice", test_list_ssplice) == NULL || CU_add_test(p_suite, "test_lsplice", test_list_lsplice) == NULL || CU_add_test(p_suite, "test_merge", test_list_merge) == NULL || CU_add_test(p_suite, "test_erase_if", test_list_erase_if) == NULL || CU_add_test(p_suite, "test_reverse", test_list_reverse) == NULL || CU_add_test(p_suite, "test_unique", test_list_unique) == NULL || CU_add_test(p_suite, "test_sort", test_list_sort) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("STACKV TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_stackv_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_stackv_ctorl) == NULL || CU_add_test(p_suite, "test_push", test_stackv_push) == NULL || CU_add_test(p_suite, "test_pop", test_stackv_pop) == NULL || CU_add_test(p_suite, "test_swap", test_stackv_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("QUEUED TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_queued_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_queued_ctorl) == NULL || CU_add_test(p_suite, "test_push", test_queued_push) == NULL || CU_add_test(p_suite, "test_pop", test_queued_pop) == NULL || CU_add_test(p_suite, "test_front", test_queued_front) == NULL || CU_add_test(p_suite, "test_back", test_queued_back) == NULL || CU_add_test(p_suite, "test_swap", test_queued_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("CIRCULAR ARRAY TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_circular_array_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_circular_array_ctorl) == NULL || CU_add_test(p_suite, "test_push_back", test_circular_array_push_back) == NULL || CU_add_test(p_suite, "test_push_front", test_circular_array_push_front) == NULL || CU_add_test(p_suite, "test_insert", test_circular_array_insert) == NULL || CU_add_test(p_suite, "test_get", test_circular_array_get) == NULL || CU_add_test(p_suite, "test_at", test_circular_array_at) == NULL || CU_add_test(p_suite, "test_set", test_circular_array_set) == NULL || CU_add_test(p_suite, "test_front", test_circular_array_front) == NULL || CU_add_test(p_suite, "test_back", test_circular_array_back) == NULL || CU_add_test(p_suite, "test_pop_back", test_circular_array_pop_back) == NULL || CU_add_test(p_suite, "test_pop_front", test_circular_array_pop_front) == NULL || CU_add_test(p_suite, "test_swap", test_circular_array_swap) == NULL || CU_add_test(p_suite, "test_erase", test_circular_array_erase) == NULL || CU_add_test(p_suite, "test_clear", test_circular_array_clear) == NULL || CU_add_test(p_suite, "test_pop_push", test_circular_array_pop_push) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("DEQUE TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_deque_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_deque_ctorl) == NULL || CU_add_test(p_suite, "test_push_back", test_deque_push_back) == NULL || CU_add_test(p_suite, "test_push_front", test_deque_push_front) == NULL || CU_add_test(p_suite, "test_insert", test_deque_insert) == NULL || CU_add_test(p_suite, "test_get", test_deque_get) == NULL || CU_add_test(p_suite, "test_set", test_deque_set) == NULL || CU_add_test(p_suite, "test_front", test_deque_front) == NULL || CU_add_test(p_suite, "test_back", test_deque_back) == NULL || CU_add_test(p_suite, "test_pop_back", test_deque_pop_back) == NULL || CU_add_test(p_suite, "test_pop_front", test_deque_pop_front) == NULL || CU_add_test(p_suite, "test_swap", test_deque_swap) == NULL || CU_add_test(p_suite, "test_erase", test_deque_erase) == NULL || CU_add_test(p_suite, "test_clear", test_deque_clear) == NULL || CU_add_test(p_suite, "test_pop_push", test_deque_pop_push) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("HEAP TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_heap_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_heap_ctorl) == NULL || CU_add_test(p_suite, "test_top", test_heap_top) == NULL || CU_add_test(p_suite, "test_extract_top", test_heap_extract_top) == NULL || CU_add_test(p_suite, "test_insert", test_heap_insert) == NULL || CU_add_test(p_suite, "test_change_key", test_heap_change_key) == NULL || CU_add_test(p_suite, "test_merge", test_heap_merge) == NULL || CU_add_test(p_suite, "test_swap", test_heap_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("BINOMIAL HEAP TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_binomial_heap_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_binomial_heap_ctorl) == NULL || CU_add_test(p_suite, "test_dtor", test_binomial_heap_dtor) == NULL || CU_add_test(p_suite, "test_top", test_binomial_heap_top) == NULL || CU_add_test(p_suite, "test_extract_top", test_binomial_heap_extract_top) == NULL || CU_add_test(p_suite, "test_insert", test_binomial_heap_insert) == NULL || CU_add_test(p_suite, "test_change_key", test_binomial_heap_change_key) == NULL || CU_add_test(p_suite, "test_merge", test_binomial_heap_merge) == NULL || CU_add_test(p_suite, "test_swap", test_binomial_heap_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("PAIRING HEAP TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_pairing_heap_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_pairing_heap_ctorl) == NULL || CU_add_test(p_suite, "test_dtor", test_pairing_heap_dtor) == NULL || CU_add_test(p_suite, "test_top", test_pairing_heap_top) == NULL || CU_add_test(p_suite, "test_extract_top", test_pairing_heap_extract_top) == NULL || CU_add_test(p_suite, "test_insert", test_pairing_heap_insert) == NULL || CU_add_test(p_suite, "test_change_key", test_pairing_heap_change_key) == NULL || CU_add_test(p_suite, "test_merge", test_pairing_heap_merge) == NULL || CU_add_test(p_suite, "test_swap", test_pairing_heap_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("PRIORITY QUEUE TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_priority_queue_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_priority_queue_ctorl) == NULL || CU_add_test(p_suite, "test_push", test_priority_queue_push) == NULL || CU_add_test(p_suite, "test_pop", test_priority_queue_pop) == NULL || CU_add_test(p_suite, "test_top", test_priority_queue_top) == NULL || CU_add_test(p_suite, "test_swap", test_priority_queue_swap) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("TREAP TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_treap_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_treap_ctorl) == NULL || CU_add_test(p_suite, "test_insert", test_treap_insert) == NULL || CU_add_test(p_suite, "test_swap", test_treap_swap) == NULL || CU_add_test(p_suite, "test_get", test_treap_get) == NULL || CU_add_test(p_suite, "test_count", test_treap_count) == NULL || CU_add_test(p_suite, "test_find", test_treap_find) == NULL || CU_add_test(p_suite, "test_clear", test_treap_clear) == NULL || CU_add_test(p_suite, "test_insert_or_assign", test_treap_insert_or_assign) == NULL || CU_add_test(p_suite, "test_erase", test_treap_erase) == NULL || CU_add_test(p_suite, "test_iterators", test_treap_iterators) == NULL || CU_add_test(p_suite, "test_height", test_treap_height) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("HASH TABLE TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_hash_table_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_hash_table_ctorl) == NULL || CU_add_test(p_suite, "test_get", test_hash_table_get) == NULL || CU_add_test(p_suite, "test_count", test_hash_table_count) == NULL || CU_add_test(p_suite, "test_find", test_hash_table_find) == NULL || CU_add_test(p_suite, "test_clear", test_hash_table_clear) == NULL || CU_add_test(p_suite, "test_insert", test_hash_table_insert) == NULL || CU_add_test(p_suite, "test_insert_or_assign", test_hash_table_insert_or_assign) == NULL || CU_add_test(p_suite, "test_erase", test_hash_table_erase) == NULL || CU_add_test(p_suite, "test_swap", test_hash_table_swap) == NULL || CU_add_test(p_suite, "test_rehash", test_hash_table_rehash) == NULL || CU_add_test(p_suite, "test_reserve", test_hash_table_reserve) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("SPLAY TREE TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_splay_tree_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_splay_tree_ctorl) == NULL || CU_add_test(p_suite, "test_insert", test_splay_tree_insert) == NULL || CU_add_test(p_suite, "test_swap", test_splay_tree_swap) == NULL || CU_add_test(p_suite, "test_get", test_splay_tree_get) == NULL || CU_add_test(p_suite, "test_count", test_splay_tree_count) == NULL || CU_add_test(p_suite, "test_find", test_splay_tree_find) == NULL || CU_add_test(p_suite, "test_clear", test_splay_tree_clear) == NULL || CU_add_test(p_suite, "test_insert_or_assign", test_splay_tree_insert_or_assign) == NULL || CU_add_test(p_suite, "test_erase", test_splay_tree_erase) == NULL || CU_add_test(p_suite, "test_iterators", test_splay_tree_iterators) == NULL || CU_add_test(p_suite, "test_height", test_splay_tree_height) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("AVL TREE TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_avl_tree_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_avl_tree_ctorl) == NULL || CU_add_test(p_suite, "test_insert", test_avl_tree_insert) == NULL || CU_add_test(p_suite, "test_swap", test_avl_tree_swap) == NULL || CU_add_test(p_suite, "test_get", test_avl_tree_get) == NULL || CU_add_test(p_suite, "test_count", test_avl_tree_count) == NULL || CU_add_test(p_suite, "test_find", test_avl_tree_find) == NULL || CU_add_test(p_suite, "test_clear", test_avl_tree_clear) == NULL || CU_add_test(p_suite, "test_insert_or_assign", test_avl_tree_insert_or_assign) == NULL || CU_add_test(p_suite, "test_erase", test_avl_tree_erase) == NULL || CU_add_test(p_suite, "test_iterators", test_avl_tree_iterators) == NULL || CU_add_test(p_suite, "test_height", test_avl_tree_height) == NULL) { CU_cleanup_registry(); return CU_get_error(); } p_suite = CU_add_suite("MAP TESTS", NULL, NULL); if (p_suite == NULL) { CU_cleanup_registry(); return CU_get_error(); } if (CU_add_test(p_suite, "test_ctor", test_map_ctor) == NULL || CU_add_test(p_suite, "test_ctorl", test_map_ctorl) == NULL || CU_add_test(p_suite, "test_insert", test_map_insert) == NULL || CU_add_test(p_suite, "test_swap", test_map_swap) == NULL || CU_add_test(p_suite, "test_get", test_map_get) == NULL || CU_add_test(p_suite, "test_count", test_map_count) == NULL || CU_add_test(p_suite, "test_find", test_map_find) == NULL || CU_add_test(p_suite, "test_clear", test_map_clear) == NULL || CU_add_test(p_suite, "test_insert_or_assign", test_map_insert_or_assign) == NULL || CU_add_test(p_suite, "test_erase", test_map_erase) == NULL || CU_add_test(p_suite, "test_iterators", test_map_iterators) == NULL || CU_add_test(p_suite, "test_iter_type", test_map_iter_type) == NULL) { CU_cleanup_registry(); return CU_get_error(); } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); CU_cleanup_registry(); return CU_get_error(); }
maksimandrianov/cdstructures
tests/test-hash-table.c
<filename>tests/test-hash-table.c // The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/casts.h" #include "cdcontainers/hash-table.h" #include <assert.h> #include <float.h> #include <stdarg.h> #include <stdio.h> #include <CUnit/Basic.h> static pair_t a = {CDC_FROM_INT(0), CDC_FROM_INT(0)}; static pair_t b = {CDC_FROM_INT(1), CDC_FROM_INT(1)}; static pair_t c = {CDC_FROM_INT(2), CDC_FROM_INT(2)}; static pair_t d = {CDC_FROM_INT(3), CDC_FROM_INT(3)}; static pair_t e = {CDC_FROM_INT(4), CDC_FROM_INT(4)}; static pair_t f = {CDC_FROM_INT(5), CDC_FROM_INT(5)}; static pair_t g = {CDC_FROM_INT(6), CDC_FROM_INT(6)}; static pair_t h = {CDC_FROM_INT(7), CDC_FROM_INT(7)}; static int eq(const void *l, const void *r) { return CDC_TO_INT(l) == CDC_TO_INT(r); } static int eq_plus_1(const void *l, const void *r) { return CDC_TO_INT(l) + 1 == CDC_TO_INT(r) + 1; } static size_t hash(const void *val) { return cdc_hash_int(CDC_TO_INT(val)); } static size_t hash1(const void *val) { return cdc_hash_uint(CDC_TO_UINT(val)); } static bool hash_table_key_int_eq(hash_table_t *t, size_t count, ...) { va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { pair_t *val = va_arg(args, pair_t *); void *tmp = NULL; if (hash_table_get(t, val->first, &tmp) != CDC_STATUS_OK || tmp != val->second) { va_end(args); return false; } } va_end(args); return true; } void test_hash_table_ctor() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctor1(&t, &info, 1.0), CDC_STATUS_OK); CU_ASSERT(hash_table_empty(t)); hash_table_dtor(t); } void test_hash_table_ctorl() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, &c, &d, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 4); CU_ASSERT(hash_table_key_int_eq(t, 4, &a, &b, &c, &d)); hash_table_dtor(t); } void test_hash_table_get() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 8); CU_ASSERT(hash_table_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); void *value = NULL; CU_ASSERT_EQUAL(hash_table_get(t, CDC_FROM_INT(10), &value), CDC_STATUS_NOT_FOUND); hash_table_dtor(t); } void test_hash_table_count() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 2); CU_ASSERT_EQUAL(hash_table_count(t, a.first), 1); CU_ASSERT_EQUAL(hash_table_count(t, b.first), 1); CU_ASSERT_EQUAL(hash_table_count(t, CDC_FROM_INT(10)), 0); hash_table_dtor(t); } void test_hash_table_find() { hash_table_t *t = NULL; hash_table_iter_t it = CDC_INIT_STRUCT; hash_table_iter_t it_end = CDC_INIT_STRUCT; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, &c, &d, &g, CDC_END), CDC_STATUS_OK); hash_table_find(t, a.first, &it); CU_ASSERT_EQUAL(hash_table_iter_value(&it), a.second); hash_table_find(t, b.first, &it); CU_ASSERT_EQUAL(hash_table_iter_value(&it), b.second); hash_table_find(t, g.first, &it); CU_ASSERT_EQUAL(hash_table_iter_value(&it), g.second); hash_table_find(t, h.first, &it); hash_table_end(t, &it_end); CU_ASSERT(hash_table_iter_is_eq(&it, &it_end)); hash_table_dtor(t); } void test_hash_table_clear() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 2); hash_table_clear(t); CU_ASSERT(hash_table_empty(t)); hash_table_clear(t); CU_ASSERT(hash_table_empty(t)); hash_table_dtor(t); } void test_hash_table_insert() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctor1(&t, &info, 1.0), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_insert(t, a.first, a.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 1); CU_ASSERT(hash_table_key_int_eq(t, 1, &a)); CU_ASSERT_EQUAL(hash_table_insert(t, a.first, b.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 1); void *value = NULL; CU_ASSERT_EQUAL(hash_table_get(t, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, a.second); CU_ASSERT(hash_table_key_int_eq(t, 1, &a)); CU_ASSERT_EQUAL(hash_table_insert(t, b.first, b.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 2); CU_ASSERT(hash_table_key_int_eq(t, 2, &a, &b)); CU_ASSERT_EQUAL(hash_table_insert(t, c.first, c.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 3); CU_ASSERT(hash_table_key_int_eq(t, 3, &a, &b, &c)); CU_ASSERT_EQUAL(hash_table_insert(t, d.first, d.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 4); CU_ASSERT(hash_table_key_int_eq(t, 4, &a, &b, &c, &d)); CU_ASSERT_EQUAL(hash_table_insert(t, e.first, e.second, NULL, NULL), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 5); CU_ASSERT(hash_table_key_int_eq(t, 5, &a, &b, &c, &d, &e)); hash_table_dtor(t); } void test_hash_table_insert_or_assign() { hash_table_t *t = NULL; hash_table_iter_t it = CDC_INIT_STRUCT; bool inserted = false; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctor1(&t, &info, 1.0), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_insert_or_assign(t, a.first, a.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 1); CU_ASSERT_EQUAL(hash_table_iter_value(&it), a.second); CU_ASSERT(inserted); CU_ASSERT_EQUAL(hash_table_insert_or_assign(t, a.first, b.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 1); void *value = NULL; CU_ASSERT_EQUAL(hash_table_get(t, a.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, b.second); CU_ASSERT_EQUAL(hash_table_iter_value(&it), b.second); CU_ASSERT(!inserted); CU_ASSERT_EQUAL(hash_table_insert_or_assign(t, c.first, c.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 2); CU_ASSERT_EQUAL(hash_table_iter_value(&it), c.second); CU_ASSERT(inserted); CU_ASSERT_EQUAL(hash_table_insert_or_assign(t, c.first, d.second, &it, &inserted), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 2); CU_ASSERT_EQUAL(hash_table_get(t, c.first, &value), CDC_STATUS_OK); CU_ASSERT_EQUAL(value, d.second); CU_ASSERT_EQUAL(hash_table_iter_value(&it), d.second); CU_ASSERT(!inserted); hash_table_dtor(t); } void test_hash_table_erase() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; void *value = NULL; CU_ASSERT_EQUAL(hash_table_ctorl1(&t, &info, 1.0, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 8); CU_ASSERT(hash_table_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, a.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, a.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(hash_table_key_int_eq(t, 7, &b, &c, &d, &g, &h, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, h.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, h.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 6); CU_ASSERT(hash_table_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, h.first), 0); CU_ASSERT_EQUAL(hash_table_size(t), 6); CU_ASSERT(hash_table_key_int_eq(t, 6, &b, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, b.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, b.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 5); CU_ASSERT(hash_table_key_int_eq(t, 5, &c, &d, &g, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, c.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, c.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 4); CU_ASSERT(hash_table_key_int_eq(t, 4, &d, &g, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, d.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, d.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 3); CU_ASSERT(hash_table_key_int_eq(t, 3, &g, &e, &f)); CU_ASSERT_EQUAL(hash_table_erase(t, f.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, f.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 2); CU_ASSERT(hash_table_key_int_eq(t, 2, &g, &e)); CU_ASSERT_EQUAL(hash_table_erase(t, e.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, e.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT_EQUAL(hash_table_size(t), 1); CU_ASSERT(hash_table_key_int_eq(t, 1, &g)); CU_ASSERT_EQUAL(hash_table_erase(t, g.first), 1); CU_ASSERT_EQUAL(hash_table_get(t, g.first, &value), CDC_STATUS_NOT_FOUND); CU_ASSERT(hash_table_empty(t)); hash_table_dtor(t); } void test_hash_table_swap() { hash_table_t *ta = NULL; hash_table_t *tb = NULL; double lf_ta = 1.0; double lf_tb = 2.0; data_info_t infoa = CDC_INIT_STRUCT; infoa.eq = eq; infoa.hash = hash; data_info_t infob = CDC_INIT_STRUCT; infob.eq = eq_plus_1; infob.hash = hash1; CU_ASSERT_EQUAL(hash_table_ctorl1(&ta, &infoa, lf_ta, &a, &b, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_ctorl1(&tb, &infob, lf_tb, &c, &d, CDC_END), CDC_STATUS_OK); hash_table_swap(ta, tb); CU_ASSERT_EQUAL(ta->dinfo->eq, eq_plus_1); CU_ASSERT_EQUAL(ta->dinfo->hash, hash1); CU_ASSERT_EQUAL(hash_table_max_load_factor(ta), lf_tb); CU_ASSERT(hash_table_key_int_eq(ta, 2, &c, &d)); CU_ASSERT_EQUAL(tb->dinfo->eq, eq); CU_ASSERT_EQUAL(tb->dinfo->hash, hash); CU_ASSERT_EQUAL(hash_table_max_load_factor(tb), lf_ta); CU_ASSERT(hash_table_key_int_eq(tb, 2, &a, &b)); hash_table_dtor(ta); hash_table_dtor(tb); } void test_hash_table_rehash() { hash_table_t *t = NULL; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctorl(&t, &info, 0.5, &a, &b, &c, &d, &g, &h, &e, &f, CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_size(t), 8); CU_ASSERT(hash_table_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); size_t bcount = hash_table_bucket_count(t) * 100; CU_ASSERT_EQUAL(hash_table_rehash(t, bcount), CDC_STATUS_OK); CU_ASSERT(hash_table_bucket_count(t) >= bcount); CU_ASSERT_EQUAL(hash_table_size(t), 8); CU_ASSERT(hash_table_key_int_eq(t, 8, &a, &b, &c, &d, &g, &h, &e, &f)); hash_table_dtor(t); } void test_hash_table_reserve() { hash_table_t *t = NULL; size_t count = 100; data_info_t info = CDC_INIT_STRUCT; info.eq = eq; info.hash = hash; CU_ASSERT_EQUAL(hash_table_ctor1(&t, &info, 1.0), CDC_STATUS_OK); CU_ASSERT_EQUAL(hash_table_reserve(t, count), CDC_STATUS_OK); CU_ASSERT((size_t)(hash_table_bucket_count(t) * cdc_hash_table_max_load_factor(t)) >= count); hash_table_dtor(t); }
maksimandrianov/cdstructures
include/cdcontainers/heap.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_heap is a struct and functions that provide a binary heap */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_HEAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_HEAP_H #include <cdcontainers/array.h> #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_heap struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_heap { struct cdc_array *array; }; /** * @brief The cdc_heap_iter struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_heap_iter { struct cdc_array *container; size_t current; }; /** * @brief Constructs an empty heap. * @param h - cdc_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_heap_ctor(struct cdc_heap **h, struct cdc_data_info *info); /** * @brief Constructs a heap, initialized by an arbitrary number of pointers. The * last item must be NULL. * @param h - cdc_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_heap_ctorl(struct cdc_heap **h, struct cdc_data_info *info, ...); /** * @brief Constructs a heap, initialized by args. The last item must be NULL. * @param h - cdc_heap * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_heap_ctorv(struct cdc_heap **h, struct cdc_data_info *info, va_list args); /** * @brief Destroys the heap. * @param h - cdc_heap */ void cdc_heap_dtor(struct cdc_heap *h); // Element access /** * @brief Returns a pointer to the heap's top item. This function assumes that * the heap isn't empty. * @param h - cdc_heap * @return top item */ static inline void *cdc_heap_top(struct cdc_heap *h) { assert(h != NULL); return cdc_array_front(h->array); } // Capacity /** * @brief Returns the number of items in the heap. * @param h - cdc_heap * @return size */ static inline size_t cdc_heap_size(struct cdc_heap *h) { assert(h != NULL); return cdc_array_size(h->array); } /** * @brief Returns true if the heap has size 0; otherwise returns false. * @param h - cdc_heap * @return true if the heap has size 0; otherwise returns false */ static inline bool cdc_heap_empty(struct cdc_heap *h) { assert(h != NULL); return cdc_array_empty(h->array); } // Modifiers /** * @brief Extracts the top item from the heap. This function assumes that the * heap isn't empty. * @param h - cdc_heap */ void cdc_heap_extract_top(struct cdc_heap *h); /** * @brief Inserts element key to the heap. Write an iterator pointing to a new * element in the ret * @param h - cdc_heap * @param key * @param ret - pointer to iterator where an iterator will be written indicating * the inserted element * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_heap_riinsert(struct cdc_heap *h, void *key, struct cdc_heap_iter *ret); /** * @brief Inserts element key to the heap. * @param h - cdc_heap * @param key * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_heap_insert(struct cdc_heap *h, void *key) { assert(h != NULL); return cdc_heap_riinsert(h, key, NULL); } /** * @brief Changes the item key on the pos position in the heap. * @param h - cdc_heap * @param pos - iterator that indicates the item with key that you want to * change * @param key */ void cdc_heap_change_key(struct cdc_heap *h, struct cdc_heap_iter *pos, void *key); /** * @brief Removes all the elements from the heap. * @param h - cdc_heap */ void cdc_heap_clear(struct cdc_heap *h); /** * @brief Swaps heaps a and b. This operation is very fast and never fails. * @param a - cdc_heap * @param b - cdc_heap */ void cdc_heap_swap(struct cdc_heap *a, struct cdc_heap *b); // Operations /** * @brief Merges two heaps. In the heap h will be the result of the merger, * and the heap other will remain empty. * @param h - cdc_heap * @param other - other cdc_heap */ enum cdc_stat cdc_heap_merge(struct cdc_heap *h, struct cdc_heap *other); /** * @brief Checks the heap property. * @param h - cdc_heap * @return result of the check */ bool cdc_heap_is_heap(struct cdc_heap *h); // Iterators /** * @brief Returns a pointer to the key of current item. */ static inline void *cdc_heap_iter_data(struct cdc_heap_iter *it) { assert(it != NULL); return cdc_array_get(it->container, it->current); } /** * @brief Returns false if the iterator it1 equal to the iterator it2, * otherwise returns false */ static inline bool cdc_heap_iter_is_eq(struct cdc_heap_iter *it1, struct cdc_heap_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->current == it2->current; } // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_heap heap_t; typedef struct cdc_heap_iter heap_iter_t; #define heap_ctor(...) cdc_heap_ctor(__VA_ARGS__) #define heap_ctorl(...) cdc_heap_ctorl(__VA_ARGS__) #define heap_ctorv(...) cdc_heap_ctorv(__VA_ARGS__) #define heap_dtor(...) cdc_heap_dtor(__VA_ARGS__) // Element access #define heap_top(...) cdc_heap_top(__VA_ARGS__) // Capacity #define heap_empty(...) cdc_heap_empty(__VA_ARGS__) #define heap_size(...) cdc_heap_size(__VA_ARGS__) // Modifiers #define heap_extract_top(...) cdc_heap_extract_top(__VA_ARGS__) #define heap_riinsert(...) cdc_heap_riinsert(__VA_ARGS__) #define heap_insert(...) cdc_heap_insert(__VA_ARGS__) #define heap_change_key(...) cdc_heap_change_key(__VA_ARGS__) #define heap_clear(...) cdc_heap_clear(__VA_ARGS__) #define heap_swap(...) cdc_heap_swap(__VA_ARGS__) // Operations #define heap_merge(...) cdc_heap_merge(__VA_ARGS__) #define heap_is_heap(...) cdc_heap_is_heap(__VA_ARGS__) // Iterators #define heap_iter_data(...) cdc_heap_iter_data(__VA_ARGS__) #define heap_iter_is_eq(...) cdc_heap_iter_is_eq(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_HEAP_H
maksimandrianov/cdstructures
include/cdcontainers/tables/imap.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_map_table is a map interface */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IMAP_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IMAP_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_map_iter_table struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_map_iter_table { void *(*ctor)(); void (*dtor)(void *it); enum cdc_iterator_type (*type)(); void (*next)(void *it); void (*prev)(void *it); bool (*has_next)(void *it); bool (*has_prev)(void *it); void *(*key)(void *it); void *(*value)(void *it); struct cdc_pair (*key_value)(void *it); bool (*eq)(void *it1, void *it2); }; /** * @brief The cdc_map_table struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_map_table { enum cdc_stat (*ctor)(void **cntr, struct cdc_data_info *info); enum cdc_stat (*ctorv)(void **cntr, struct cdc_data_info *info, va_list args); void (*dtor)(void *cntr); enum cdc_stat (*get)(void *cntr, void *key, void **value); size_t (*count)(void *cntr, void *key); void (*find)(void *cntr, void *key, void *it); size_t (*size)(void *cntr); bool (*empty)(void *cntr); void (*clear)(void *cntr); enum cdc_stat (*insert)(void *cntr, void *key, void *value, void *it, bool *inserted); enum cdc_stat (*insert_or_assign)(void *cntr, void *key, void *value, void *it, bool *inserted); size_t (*erase)(void *cntr, void *key); void (*swap)(void *a, void *b); void (*begin)(void *cntr, void *it); void (*end)(void *cntr, void *it); const struct cdc_map_iter_table *iter_table; }; extern const struct cdc_map_table *cdc_map_avl; extern const struct cdc_map_table *cdc_map_splay; extern const struct cdc_map_table *cdc_map_treap; extern const struct cdc_map_table *cdc_map_htable; // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_map_iter_table map_iter_table_t; typedef struct cdc_map_table map_table_t; #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_INTERFACES_IMAP_H
maksimandrianov/cdstructures
tests/test-deque.c
// The MIT License (MIT) // Copyright (c) 2019 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/adapters/deque.h" #include "cdcontainers/casts.h" #include <assert.h> #include <float.h> #include <stdarg.h> #include <stdio.h> #include <CUnit/Basic.h> static bool deque_range_int_eq(deque_t *d, size_t count, ...) { assert(deque_size(d) >= count); va_list args; va_start(args, count); for (size_t i = 0; i < count; ++i) { int elem = va_arg(args, int); if (CDC_TO_INT(deque_get(d, i)) != elem) { return false; } } return true; } static inline void deque_range_int_print(deque_t *d) { for (size_t i = 0; i < deque_size(d); ++i) { printf("%d ", CDC_TO_INT(deque_get(d, i))); } printf("\n"); } void test_deque_ctor() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *d = NULL; CU_ASSERT_EQUAL(deque_ctor(tables[t], &d, NULL), CDC_STATUS_OK); CU_ASSERT(deque_empty(d)); deque_dtor(d); } } void test_deque_ctorl() { int a = 0, b = 1, c = 2, d = 3; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, a, b, c, d)); deque_dtor(deq); } } void test_deque_push_back() { int a = 0, b = 1, c = 2; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctor(tables[t], &deq, NULL), CDC_STATUS_OK); deque_push_back(deq, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(deque_size(deq), 1); CU_ASSERT(deque_range_int_eq(deq, 1, a)); deque_push_back(deq, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(deque_size(deq), 2); CU_ASSERT(deque_range_int_eq(deq, 1, a, b)); deque_push_back(deq, CDC_FROM_INT(c)); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT(deque_range_int_eq(deq, 3, a, b, c)); deque_push_back(deq, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, a, b, c, a)); deque_push_back(deq, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(deque_size(deq), 5); CU_ASSERT(deque_range_int_eq(deq, 5, a, b, c, a, b)); deque_dtor(deq); } } void test_deque_push_front() { int a = 0, b = 1, c = 2; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctor(tables[t], &deq, NULL), CDC_STATUS_OK); CU_ASSERT(deque_empty(deq)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 1); CU_ASSERT(deque_range_int_eq(deq, 1, a)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 2); CU_ASSERT(deque_range_int_eq(deq, 2, b, a)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT(deque_range_int_eq(deq, 3, c, b, a)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, a, c, b, a)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 5); CU_ASSERT(deque_range_int_eq(deq, 4, b, a, c, b, a)); deque_dtor(deq); } } void test_deque_get() { int a = 0, b = 1; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(deque_get(deq, 0)), a); CU_ASSERT_EQUAL(CDC_TO_INT(deque_get(deq, 1)), b); deque_dtor(deq); } } void test_deque_set() { int a = 1, b = 2; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *d = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); deque_set(d, 0, CDC_FROM_INT(b)); CU_ASSERT(deque_range_int_eq(d, 2, b, b)); deque_set(d, 1, CDC_FROM_INT(a)); CU_ASSERT(deque_range_int_eq(d, 2, b, a)); deque_dtor(d); } } void test_deque_front() { int a = 1, b = 2; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *d = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(deque_front(d)), a); CU_ASSERT_EQUAL(deque_push_front(d, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(deque_front(d)), b); deque_dtor(d); } } void test_deque_back() { int a = 1, b = 2; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *d = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(deque_back(d)), b); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(CDC_TO_INT(deque_back(d)), a); deque_dtor(d); } } void test_deque_pop_back() { int a = 0, b = 1, c = 2, d = 3; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = deque_back(deq); deque_pop_back(deq); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); elem = deque_back(deq); deque_pop_back(deq); CU_ASSERT_EQUAL(deque_size(deq), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = deque_back(deq); deque_pop_back(deq); CU_ASSERT_EQUAL(deque_size(deq), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = deque_back(deq); deque_pop_back(deq); CU_ASSERT(deque_empty(deq)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); deque_dtor(deq); } } void test_deque_pop_front() { int a = 0, b = 1, c = 2, d = 3; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = deque_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); elem = deque_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_size(deq), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = deque_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_size(deq), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = deque_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_size(deq), 0); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); deque_dtor(deq); } } void test_deque_swap() { int a = 0, b = 1, c = 2, d = 3; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *v = NULL; deque_t *w = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &v, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_ctorl(tables[t], &w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); deque_swap(v, w); CU_ASSERT_EQUAL(deque_size(v), 2); CU_ASSERT(deque_range_int_eq(v, 2, a, d)); CU_ASSERT_EQUAL(deque_size(w), 4); CU_ASSERT(deque_range_int_eq(w, 4, a, b, c, d)); deque_dtor(v); deque_dtor(w); } } void test_deque_insert() { deque_t *deq = NULL; int a = 1, b = 2; int i1 = 3, i2 = 4, i3 = 5; int v0 = -1, v1 = 0, v2 = 1, v3 = 2, v4 = 3, v5 = 4, v6 = 5; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_insert(deq, 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, v1, v2, v0, v3, v4, v5, v6)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); CU_ASSERT(deque_range_int_eq(deq, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v2, v0, v3, v4, v5, v6)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v4, v5, v6, v1, v2, v3)); CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, v4, v0, v5, v6, v1, v2, v3)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v5)), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v2, v3, v4, v5, v4, v5)); CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, v2, v0, v3, v4, v5, v4, v5)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT(deque_range_int_eq(deq, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq) - 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v2, v3, v4, v0, v5, v6)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); CU_ASSERT(deque_range_int_eq(deq, 5, v2, v3, v4, v5, v6)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq) - 2, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v2, v3, v4, v0, v5, v6)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v4, v5, v6, v1, v2, v3)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq) - 1, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, v4, v5, v6, v1, v2, v0, v3)); deque_dtor(deq); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_END), CDC_STATUS_OK); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v6)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 6, v1, v3, v4, v5, v6, v5)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq) - 3, CDC_FROM_INT(v0)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, v1, v3, v4, v0, v5, v6, v5)); deque_dtor(deq); } } for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { int insert_count = 100; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_insert(deq, 0, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT(deque_range_int_eq(deq, 3, i1, a, b)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq), CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, i1, a, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, 2, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 5); CU_ASSERT(deque_range_int_eq(deq, 5, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 14, i3, i1, b, a, i3, i2, i1, b, a, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 15, i3, a, i1, b, a, i3, i2, i1, b, a, i1, a, i3, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq) - 2, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 16, i3, a, i1, b, a, i3, i2, i1, b, a, i1, a, i3, a, b, i2)); deque_clear(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(0)), CDC_STATUS_OK); for (int i = 0; i <= insert_count; ++i) { CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(i)), CDC_STATUS_OK); } CU_ASSERT_EQUAL(deque_get(deq, 0), CDC_FROM_INT(0)); for (int i = insert_count; i >= 0; --i) { CU_ASSERT_EQUAL(deque_get(deq, (size_t)(insert_count - i + 1)), CDC_FROM_INT(i)); } deque_dtor(deq); } } void test_deque_erase() { deque_t *d = NULL; int v1 = 0, v2 = 1, v3 = 2, v4 = 3, v5 = 4, v6 = 5; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_erase(d, 2); CU_ASSERT(deque_range_int_eq(d, 5, v1, v2, v4, v5, v6)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); CU_ASSERT(deque_range_int_eq(d, 5, v2, v3, v4, v5, v6)); deque_erase(d, 1); CU_ASSERT(deque_range_int_eq(d, 4, v2, v4, v5, v6)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(d, 6, v4, v5, v6, v1, v2, v3)); deque_erase(d, 1); CU_ASSERT(deque_range_int_eq(d, 5, v4, v6, v1, v2, v3)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v4)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(d, 6, v2, v3, v4, v5, v4, v5)); deque_erase(d, 1); CU_ASSERT(deque_range_int_eq(d, 5, v2, v4, v5, v4, v5)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL(deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); CU_ASSERT(deque_range_int_eq(d, 5, v2, v3, v4, v5, v6)); deque_erase(d, deque_size(d) - 2); CU_ASSERT(deque_range_int_eq(d, 4, v2, v3, v4, v6)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); CU_ASSERT(deque_range_int_eq(d, 5, v2, v3, v4, v5, v6)); deque_erase(d, deque_size(d) - 2); CU_ASSERT(deque_range_int_eq(d, 4, v2, v3, v4, v6)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL( deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_FROM_INT(v6), CDC_END), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v3)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(d, 6, v4, v5, v6, v1, v2, v3)); deque_erase(d, deque_size(d) - 2); CU_ASSERT(deque_range_int_eq(d, 5, v4, v5, v6, v1, v3)); deque_dtor(d); } } { for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { CU_ASSERT_EQUAL(deque_ctorl(tables[t], &d, NULL, CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v1), CDC_FROM_INT(v2), CDC_FROM_INT(v3), CDC_FROM_INT(v4), CDC_FROM_INT(v5), CDC_END), CDC_STATUS_OK); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); deque_pop_front(d); CU_ASSERT_EQUAL(deque_push_front(d, CDC_FROM_INT(v1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v6)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(d, CDC_FROM_INT(v5)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(d, 6, v1, v3, v4, v5, v6, v5)); deque_erase(d, deque_size(d) - 3); CU_ASSERT(deque_range_int_eq(d, 5, v1, v3, v4, v6, v5)); deque_dtor(d); } } { int a = 0, b = 1, c = 2, d = 3, erase_count = 100; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL( deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); deque_erase(deq, 2); CU_ASSERT_EQUAL(deque_size(deq), 6); CU_ASSERT(deque_range_int_eq(deq, 3, a, b, d, a, b, c)); deque_erase(deq, 4); CU_ASSERT_EQUAL(deque_size(deq), 5); CU_ASSERT(deque_range_int_eq(deq, 5, a, b, d, a, c)); deque_erase(deq, 0); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, b, d, a, c)); deque_erase(deq, deque_size(deq) - 1); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT(deque_range_int_eq(deq, 3, b, d, a)); deque_clear(deq); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 4, d, c, b, a)); deque_erase(deq, 1); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT(deque_range_int_eq(deq, 3, d, b, a)); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(c)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(d)), CDC_STATUS_OK); CU_ASSERT(deque_range_int_eq(deq, 7, d, d, b, a, d, c, a)); deque_erase(deq, deque_size(deq) - 2); CU_ASSERT_EQUAL(deque_size(deq), 6); CU_ASSERT(deque_range_int_eq(deq, 6, d, d, b, a, d, a)); deque_clear(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(0)), CDC_STATUS_OK); for (int i = 0; i <= erase_count; ++i) { CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(i)), CDC_STATUS_OK); } for (int i = erase_count; i >= 0; --i) { deque_erase(deq, 1); } CU_ASSERT_EQUAL(deque_size(deq), 1); CU_ASSERT_EQUAL(deque_get(deq, 0), CDC_FROM_INT(0)); deque_dtor(deq); } } } void test_deque_clear() { int a = 0, b = 1, c = 2, d = 3; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); deque_clear(deq); CU_ASSERT(deque_empty(deq)); deque_dtor(deq); } } void test_deque_pop_push() { int a = 1, b = 2, c = 3; int i1 = 3, i2 = 4, i3 = 5; const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { deque_t *deq = NULL; CU_ASSERT_EQUAL(deque_ctorl(tables[t], &deq, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 3); for (int i = 0; i < 5; ++i) { CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); deque_pop_back(deq); CU_ASSERT_EQUAL(deque_push_front(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); deque_pop_back(deq); } CU_ASSERT(deque_range_int_eq(deq, 3, b, a, b)); CU_ASSERT_EQUAL(deque_size(deq), 3); for (int i = 0; i < 5; ++i) { CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(a)), CDC_STATUS_OK); deque_pop_front(deq); CU_ASSERT_EQUAL(deque_push_back(deq, CDC_FROM_INT(b)), CDC_STATUS_OK); deque_pop_front(deq); } CU_ASSERT(deque_range_int_eq(deq, 3, b, a, b)); CU_ASSERT_EQUAL(deque_size(deq), 3); CU_ASSERT_EQUAL(deque_insert(deq, 0, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 4); CU_ASSERT(deque_range_int_eq(deq, 4, i1, b, a, b)); CU_ASSERT_EQUAL(deque_insert(deq, deque_size(deq), CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 5); CU_ASSERT(deque_range_int_eq(deq, 5, i1, b, a, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, 2, CDC_FROM_INT(i3)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 6); CU_ASSERT(deque_range_int_eq(deq, 6, i1, b, i3, a, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, 4, CDC_FROM_INT(i1)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 7); CU_ASSERT(deque_range_int_eq(deq, 7, i1, b, i3, a, i1, b, i2)); CU_ASSERT_EQUAL(deque_insert(deq, 1, CDC_FROM_INT(i2)), CDC_STATUS_OK); CU_ASSERT_EQUAL(deque_size(deq), 8); CU_ASSERT(deque_range_int_eq(deq, 8, i1, i2, b, i3, a, i1, b, i2)); deque_dtor(deq); } }
maksimandrianov/cdstructures
include/cdcontainers/adapters/deque.h
<gh_stars>10-100 // The MIT License (MIT) // Copyright (c) 2019 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_deque is a struct and functions that provide a * double-ended queue. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_DEQUE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_DEQUE_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <cdcontainers/tables/isequence.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @defgroup cdc_deque * @brief The cdc_deque is a struct and functions that provide a double-ended queue. * @{ */ /** * @brief The cdc_deque struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_deque { void *container; const struct cdc_sequence_table *table; }; // Base /** * @defgroup cdc_deque_base Base * @{ */ /** * @brief Constructs an empty deque. * @param table - method table for a particular implementation * @param d - cdc_deque * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_deque_ctor(const struct cdc_sequence_table *table, struct cdc_deque **d, struct cdc_data_info *info); /** * @brief Constructs a deque, initialized by an arbitrary number of * pointers. The last item must be NULL. * @param table - method table for a particular implementation * @param d - cdc_deque * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_deque_ctorl(const struct cdc_sequence_table *table, struct cdc_deque **d, struct cdc_data_info *info, ...); /** * @brief Constructs a deque, initialized by args. The last item must * be NULL. * @param table - method table for a particular implementation * @param d - cdc_deque * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_deque_ctorv(const struct cdc_sequence_table *table, struct cdc_deque **d, struct cdc_data_info *info, va_list args); /** * @brief Destroys the deque. * @param d - cdc_deque */ void cdc_deque_dtor(struct cdc_deque *d); /** @} */ // Element access /** * @defgroup cdc_deque_element_access Element access * @{ */ /** * @brief Returns the item at index position index in the deque. Index * must be a valid index position in the deque. * @param d - cdc_deque * @param index - index of the item to return * @return item at the index position */ static inline void *cdc_deque_get(struct cdc_deque *d, size_t index) { assert(d != NULL); return d->table->get(d->container, index); } /** * @brief Returns a pointer to the first item in the deque. * This function assumes that the deque isn't empty. * @param d - cdc_deque * @return pointer to the first item in the deque */ static inline void *cdc_deque_front(struct cdc_deque *d) { assert(d != NULL); return d->table->front(d->container); } /** * @brief Returns a pointer to the last item in the deque. * This function assumes that the deque isn't empty. * @param d - cdc_deque * @return pointer to the last item in the deque */ static inline void *cdc_deque_back(struct cdc_deque *d) { assert(d != NULL); return d->table->back(d->container); } /** @} */ // Capacity /** * @defgroup cdc_deque_capacity Capacity * @{ */ /** * @brief Returns true if the deque has size 0; otherwise returns * false. * @param d - cdc_deque * @return true if the deque has size 0; otherwise returns false */ static inline bool cdc_deque_empty(struct cdc_deque *d) { assert(d != NULL); return d->table->empty(d->container); } /** * @brief Returns the number of items in the deque. * @param d - cdc_deque * @return size */ static inline size_t cdc_deque_size(struct cdc_deque *d) { assert(d != NULL); return d->table->size(d->container); } /** @} */ // Modifiers /** * @defgroup cdc_deque_modifiers Modifiers * @{ */ /** * @brief Sets the deque at index position to the value. The function * is not called to free memory. * @param d - cdc_deque * @param index - index position where the value will be written * @param value */ static inline void cdc_deque_set(struct cdc_deque *d, size_t index, void *value) { assert(d != NULL); d->table->set(d->container, index, value); } /** * @brief Inserts value at index position in the deque. If index is 0, * the value is prepended to the deque. If index is * cdc_deque_size(), the value is appended to the deque. * @param d - cdc_deque * @param index - index position where the value will be inserted * @param value * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_deque_insert(struct cdc_deque *d, size_t index, void *value) { assert(d != NULL); return d->table->insert(d->container, index, value); } /** * @brief Removes the element at index position. Index must be a valid index * position in the deque. * @param d - cdc_deque * @param index - index position where the item will be removed */ static inline void cdc_deque_erase(struct cdc_deque *d, size_t index) { assert(d != NULL); d->table->erase(d->container, index); } /** * @brief Removes all the elements from the deque. * @param d - cdc_deque */ static inline void cdc_deque_clear(struct cdc_deque *d) { assert(d != NULL); d->table->clear(d->container); } /** * @brief Inserts value at the end of the deque. * @param d - cdc_deque * @param value * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_deque_push_back(struct cdc_deque *d, void *value) { assert(d != NULL); return d->table->push_back(d->container, value); } /** * @brief Removes the last item in the deque. * @param d - cdc_deque */ static inline void cdc_deque_pop_back(struct cdc_deque *d) { assert(d != NULL); d->table->pop_back(d->container); } /** * @brief Inserts value at the beginning of the deque. * @param d - cdc_deque * @param value * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_deque_push_front(struct cdc_deque *d, void *value) { assert(d != NULL); return d->table->push_front(d->container, value); } /** * @brief Removes the first item in the deque. * @param d - cdc_deque */ static inline void cdc_deque_pop_front(struct cdc_deque *d) { assert(d != NULL); d->table->pop_front(d->container); } /** * @brief Swaps deques a and b. This operation is very fast and never * fails. * @param a - cdc_deque * @param b - cdc_deque */ void cdc_deque_swap(struct cdc_deque *a, struct cdc_deque *b); /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_deque deque_t; // Base #define deque_ctor(...) cdc_deque_ctor(__VA_ARGS__) #define deque_ctorl(...) cdc_deque_ctorl(__VA_ARGS__) #define deque_ctorv(...) cdc_deque_ctorv(__VA_ARGS__) #define deque_dtor(...) cdc_deque_dtor(__VA_ARGS__) // Element access #define deque_get(...) cdc_deque_get(__VA_ARGS__) #define deque_front(...) cdc_deque_front(__VA_ARGS__) #define deque_back(...) cdc_deque_back(__VA_ARGS__) // Capacity #define deque_empty(...) cdc_deque_empty(__VA_ARGS__) #define deque_size(...) cdc_deque_size(__VA_ARGS__) // Modifiers #define deque_set(...) cdc_deque_set(__VA_ARGS__) #define deque_insert(...) cdc_deque_insert(__VA_ARGS__) #define deque_erase(...) cdc_deque_erase(__VA_ARGS__) #define deque_clear(...) cdc_deque_clear(__VA_ARGS__) #define deque_push_back(...) cdc_deque_push_back(__VA_ARGS__) #define deque_pop_back(...) cdc_deque_pop_back(__VA_ARGS__) #define deque_push_front(...) cdc_deque_push_front(__VA_ARGS__) #define deque_pop_front(...) cdc_deque_pop_front(__VA_ARGS__) #define deque_swap(...) cdc_deque_swap(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_DEQUE_H
maksimandrianov/cdstructures
include/cdcontainers/adapters/stack.h
// The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_stack is a struct and functions that provide a stack */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_STACK_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_STACK_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <cdcontainers/tables/isequence.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> /** * @brief The cdc_stack struct * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_stack { void *container; const struct cdc_sequence_table *table; }; /** * @brief Constructs an empty stack. * @param table - method table for a particular implementation * @param s - cdc_stack * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_stack_ctor(const struct cdc_sequence_table *table, struct cdc_stack **s, struct cdc_data_info *info); /** * @brief Constructs a stack, initialized by an arbitrary number of pointers. * The last item must be NULL. * @param table - method table for a particular implementation * @param s - cdc_stack * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_stack_ctorl(const struct cdc_sequence_table *table, struct cdc_stack **s, struct cdc_data_info *info, ...); /** * @brief Constructs a stack, initialized by args. The last item must be NULL. * @param table - method table for a particular implementation * @param s - cdc_stack * @param info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ enum cdc_stat cdc_stack_ctorv(const struct cdc_sequence_table *table, struct cdc_stack **s, struct cdc_data_info *info, va_list args); /** * @brief Destroys the stack. * @param s - cdc_stack */ void cdc_stack_dtor(struct cdc_stack *s); // Element access /** * @brief Returns a pointer to the stack's top item. This function assumes * that the stack isn't empty. * @param s - cdc_stack * @return pointer to the stack's top item */ static inline void *cdc_stack_top(struct cdc_stack *s) { assert(s != NULL); return s->table->back(s->container); } // Capacity /** * @brief Returns true if the stack has size 0; otherwise returns false. * @param s - cdc_stack * @return true if the list has size 0; otherwise returns false */ static inline bool cdc_stack_empty(struct cdc_stack *s) { assert(s != NULL); return s->table->empty(s->container); } /** * @brief Returns the number of items in the stack. * @param s - cdc_stack * @return size */ static inline size_t cdc_stack_size(struct cdc_stack *s) { assert(s != NULL); return s->table->size(s->container); } // Modifiers /** * @brief Adds element elem to the top of the stack. * @param s - cdc_stack * @param elem * @return CDC_STATUS_OK in a successful case or other value indicating * an error */ static inline enum cdc_stat cdc_stack_push(struct cdc_stack *s, void *elem) { assert(s != NULL); return s->table->push_back(s->container, elem); } /** * @brief Removes the top item from the stack. This function assumes that the * stack isn't empty. * @param s - cdc_stack */ static inline void cdc_stack_pop(struct cdc_stack *s) { assert(s != NULL); s->table->pop_back(s->container); } /** * @brief Swaps stack a and b. This operation is very fast and never fails. * @param a - cdc_stack * @param b - cdc_stack */ void cdc_stack_swap(struct cdc_stack *a, struct cdc_stack *b); // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_stack cstack_t; #define stack_ctor(...) cdc_stack_ctor(__VA_ARGS__) #define stack_ctorl(...) cdc_stack_ctorl(__VA_ARGS__) #define stack_ctorv(...) cdc_stack_ctorv(__VA_ARGS__) #define stack_dtor(...) cdc_stack_dtor(__VA_ARGS__) // Element access #define stack_top(...) cdc_stack_top(__VA_ARGS__) // Capacity #define stack_empty(...) cdc_stack_empty(__VA_ARGS__) #define stack_size(...) cdc_stack_size(__VA_ARGS__) // Modifiers #define stack_push(...) cdc_stack_push(__VA_ARGS__) #define stack_pop(...) cdc_stack_pop(__VA_ARGS__) #define stack_swap(...) cdc_stack_swap(__VA_ARGS__) #endif #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_STACK_H
maksimandrianov/cdstructures
include/cdcontainers/splay-tree.h
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /** * @file * @author <NAME> <<EMAIL>> * @brief The cdc_splay_tree is a struct and functions that provide a splay tree. */ #ifndef CDCONTAINERS_INCLUDE_CDCONTAINERS_SPLAY_TREE_H #define CDCONTAINERS_INCLUDE_CDCONTAINERS_SPLAY_TREE_H #include <cdcontainers/common.h> #include <cdcontainers/status.h> #include <assert.h> #include <stdarg.h> #include <stdbool.h> /** * @defgroup cdc_splay_tree * @brief The cdc_splay_tree is a struct and functions that provide a splay tree. * @{ */ /** * @brief The cdc_splay_tree_node is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_splay_tree_node { struct cdc_splay_tree_node *parent; struct cdc_splay_tree_node *left; struct cdc_splay_tree_node *right; void *key; void *value; }; /** * @brief The cdc_splay_tree is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_splay_tree { struct cdc_splay_tree_node *root; size_t size; struct cdc_data_info *dinfo; }; /** * @brief The cdc_splay_tree_iter is service struct. * @warning To avoid problems, do not change the structure fields in the code. * Use only special functions to access and change structure fields. */ struct cdc_splay_tree_iter { struct cdc_splay_tree *container; struct cdc_splay_tree_node *prev; struct cdc_splay_tree_node *current; }; struct cdc_pair_splay_tree_iter_bool { struct cdc_splay_tree_iter first; bool second; }; // Base /** * @defgroup cdc_splay_tree_base Base * @{ */ /** * @brief Constructs an empty splay tree. * @param[out] t - cdc_splay_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_ctor(struct cdc_splay_tree **t, struct cdc_data_info *info); /** * @brief Constructs a splay tree, initialized by an variable number of * pointers on cdc_pair's(first - key, and the second - value). The last item * must be CDC_END. * @param[out] t - cdc_splay_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. * * Example: * @code{.c} * struct cdc_splay_tree *tree = NULL; * cdc_pair value1 = {CDC_FROM_INT(1), CDC_FROM_INT(2)}; * cdc_pair value2 = {CDC_FROM_INT(3), CDC_FROM_INT(4)}; * ... * if (cdc_splay_tree_ctorl(&tree, info, &value1, &value2, CDC_END) != CDC_STATUS_OK) { * // handle error * } * @endcode */ enum cdc_stat cdc_splay_tree_ctorl(struct cdc_splay_tree **t, struct cdc_data_info *info, ...); /** * @brief Constructs a splay tree, initialized by args. The last item must be * CDC_END. * @param[out] t - cdc_splay_tree * @param[in] info - cdc_data_info * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_ctorv(struct cdc_splay_tree **t, struct cdc_data_info *info, va_list args); /** * @brief Destroys the splay tree. * @param[in] t - cdc_splay_tree */ void cdc_splay_tree_dtor(struct cdc_splay_tree *t); /** @} */ // Lookup /** * @defgroup cdc_splay_tree_lookup Lookup * @{ */ /** * @brief Returns a value that is mapped to a key. If the key does * not exist, then NULL will return. * @param[in] t - cdc_splay_tree * @param[in] key - key of the element to find * @param[out] value - pinter to the value that is mapped to a key. * @return CDC_STATUS_OK if the key is found, CDC_STATUS_NOT_FOUND otherwise. */ enum cdc_stat cdc_splay_tree_get(struct cdc_splay_tree *t, void *key, void **value); /** * @brief Returns the number of elements with key that compares equal to the * specified argument key, which is either 1 or 0 since this container does not * allow duplicates. * @param[in] t - cdc_splay_tree * @param[in] key - key value of the elements to count * @return number of elements with key key, that is either 1 or 0. */ size_t cdc_splay_tree_count(struct cdc_splay_tree *t, void *key); /** * @brief Finds an element with key equivalent to key. * @param[in] t - cdc_splay_tree * @param[in] key - key value of the element to search for * @param[out] it - pointer will be recorded iterator to an element with key * equivalent to key. If no such element is found, past-the-end iterator is * returned. */ void cdc_splay_tree_find(struct cdc_splay_tree *t, void *key, struct cdc_splay_tree_iter *it); /** @} */ // Capacity /** * @defgroup cdc_splay_tree_capacity Capacity * @{ */ /** * @brief Returns the number of items in the splay_tree. * @param[in] t - cdc_splay_tree * @return the number of items in the splay_tree. */ static inline size_t cdc_splay_tree_size(struct cdc_splay_tree *t) { assert(t != NULL); return t->size; } /** * @brief Checks if the splay tree has no elements. * @param[in] t - cdc_splay_tree * @return true if the splay tree is empty, false otherwise. */ static inline bool cdc_splay_tree_empty(struct cdc_splay_tree *t) { assert(t != NULL); return t->size == 0; } /** @} */ // Modifiers /** * @defgroup cdc_splay_tree_modifiers Modifiers * @{ */ /** * @brief Removes all the elements from the splay_tree. * @param[in] t - cdc_splay_tree */ void cdc_splay_tree_clear(struct cdc_splay_tree *t); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_splay_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair consisting of an iterator to the inserted element (or to * the element that prevented the insertion) and a bool denoting whether the * insertion took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_insert(struct cdc_splay_tree *t, void *key, void *value, struct cdc_pair_splay_tree_iter_bool *ret); /** * @brief Inserts an element into the container, if the container doesn't already * contain an element with an equivalent key. * @param[in] t - cdc_splay_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator to the inserted element (or to the element that * prevented the insertion). The pointer can be equal to NULL. * @param[out] inserted - bool denoting whether the insertion * took place. The pointer can be equal to NULL. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_insert1(struct cdc_splay_tree *t, void *key, void *value, struct cdc_splay_tree_iter *it, bool *inserted); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_splay_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] ret - pair. The bool component is true if the insertion took place and * false if the assignment took place. The iterator component is pointing at the * element that was inserted or updated. * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_insert_or_assign(struct cdc_splay_tree *t, void *key, void *value, struct cdc_pair_splay_tree_iter_bool *ret); /** * @brief Inserts an element or assigns to the current element if the key * already exists. * @param[in] t - cdc_splay_tree * @param[in] key - key of the element * @param[in] value - value of the element * @param[out] it - iterator is pointing at the element that was inserted or updated. * The pointer can be equal to NULL * @param[out] inserted - bool is true if the insertion took place and false if the * assignment took place. The pointer can be equal to NULL * @return CDC_STATUS_OK in a successful case or other value indicating * an error. */ enum cdc_stat cdc_splay_tree_insert_or_assign1(struct cdc_splay_tree *t, void *key, void *value, struct cdc_splay_tree_iter *it, bool *inserted); /** * @brief Removes the element (if one exists) with the key equivalent to key. * @param[in] t - cdc_splay_tree * @param[in] key - key value of the elements to remove * @return number of elements removed. */ size_t cdc_splay_tree_erase(struct cdc_splay_tree *t, void *key); /** * @brief Swaps splay_trees a and b. This operation is very fast and never fails. * @param[in, out] a - cdc_splay_tree * @param[in, out] b - cdc_splay_tree */ void cdc_splay_tree_swap(struct cdc_splay_tree *a, struct cdc_splay_tree *b); /** @} */ // Iterators /** * @defgroup cdc_splay_tree_iterators Iterators * @{ */ /** * @brief Initializes the iterator to the beginning. * @param t[in] - cdc_splay_tree * @param it[out] - cdc_splay_tree_iter */ void cdc_splay_tree_begin(struct cdc_splay_tree *t, struct cdc_splay_tree_iter *it); /** * @brief Initializes the iterator to the end. * @param[in] t - cdc_splay_tree * @param[out] it - cdc_splay_tree_iter */ void cdc_splay_tree_end(struct cdc_splay_tree *t, struct cdc_splay_tree_iter *it); /** @} */ // Iterators /** * @defgroup cdc_splay_tree_iter * @brief The cdc_splay_tree_iter is a struct and functions that provide a splay tree iterator. * @{ */ /** * @brief Advances the iterator to the next element in the splay tree. * @param[in] it - iterator */ void cdc_splay_tree_iter_next(struct cdc_splay_tree_iter *it); /** * @brief Advances the iterator to the previous element in the splay tree. * @param[in] it - iterator */ void cdc_splay_tree_iter_prev(struct cdc_splay_tree_iter *it); /** * @brief Returns true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element ahead of the iterator, i.e. * the iterator is not at the back of the container; otherwise returns false. */ static inline bool cdc_splay_tree_iter_has_next(struct cdc_splay_tree_iter *it) { assert(it != NULL); return it->current != NULL; } /** * @brief Returns true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. * @param[in] it - iterator * @return true if there is at least one element behind the iterator, i.e. * the iterator is not at the front of the container; otherwise returns false. */ static inline bool cdc_splay_tree_iter_has_prev(struct cdc_splay_tree_iter *it) { assert(it != NULL); return it->prev != NULL; } /** * @brief Returns an item's key. * @param[in] it - iterator * @return the item's key. */ static inline void *cdc_splay_tree_iter_key(struct cdc_splay_tree_iter *it) { assert(it != NULL); return it->current->key; } /** * @brief Returns an item's value. * @param[in] it - iterator * @return the item's value. */ static inline void *cdc_splay_tree_iter_value(struct cdc_splay_tree_iter *it) { assert(it != NULL); return it->current->value; } /** * @brief Returns a pair, where first - key, second - value. * @param[in] it - iterator * @return pair, where first - key, second - value. */ static inline struct cdc_pair cdc_splay_tree_iter_key_value(struct cdc_splay_tree_iter *it) { assert(it != NULL); struct cdc_pair pair = {it->prev->key, it->prev->value}; return pair; } /** * @brief Returns false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. * @param[in] it1 - iterator * @param[in] it2 - iterator * @return false if the iterator |it1| equal to the iterator |it2|, * otherwise returns false. */ static inline bool cdc_splay_tree_iter_is_eq(struct cdc_splay_tree_iter *it1, struct cdc_splay_tree_iter *it2) { assert(it1 != NULL); assert(it2 != NULL); return it1->container == it2->container && it1->prev == it2->prev && it1->current == it2->current; } /** @} */ // Short names #ifdef CDC_USE_SHORT_NAMES typedef struct cdc_splay_tree_node splay_tree_node_t; typedef struct cdc_splay_tree splay_tree_t; typedef struct cdc_splay_tree_iter splay_tree_iter_t; typedef struct cdc_pair_splay_tree_iter pair_splay_tree_iter_t; typedef struct cdc_pair_splay_tree_iter_bool pair_splay_tree_iter_bool_t; // Base #define splay_tree_ctor(...) cdc_splay_tree_ctor(__VA_ARGS__) #define splay_tree_ctorv(...) cdc_splay_tree_ctorv(__VA_ARGS__) #define splay_tree_ctorl(...) cdc_splay_tree_ctorl(__VA_ARGS__) #define splay_tree_dtor(...) cdc_splay_tree_dtor(__VA_ARGS__) // Lookup #define splay_tree_get(...) cdc_splay_tree_get(__VA_ARGS__) #define splay_tree_count(...) cdc_splay_tree_count(__VA_ARGS__) #define splay_tree_find(...) cdc_splay_tree_find(__VA_ARGS__) // Capacity #define splay_tree_size(...) cdc_splay_tree_size(__VA_ARGS__) #define splay_tree_empty(...) cdc_splay_tree_empty(__VA_ARGS__) // Modifiers #define splay_tree_clear(...) cdc_splay_tree_clear(__VA_ARGS__) #define splay_tree_insert(...) cdc_splay_tree_insert(__VA_ARGS__) #define splay_tree_insert1(...) cdc_splay_tree_insert1(__VA_ARGS__) #define splay_tree_insert_or_assign(...) cdc_splay_tree_insert_or_assign(__VA_ARGS__) #define splay_tree_insert_or_assign1(...) cdc_splay_tree_insert_or_assign1(__VA_ARGS__) #define splay_tree_erase(...) cdc_splay_tree_erase(__VA_ARGS__) #define splay_tree_swap(...) cdc_splay_tree_swap(__VA_ARGS__) // Iterators #define splay_tree_begin(...) cdc_splay_tree_begin(__VA_ARGS__) #define splay_tree_end(...) cdc_splay_tree_end(__VA_ARGS__) // Iterators #define splay_tree_iter_next(...) cdc_splay_tree_iter_next(__VA_ARGS__) #define splay_tree_iter_prev(...) cdc_splay_tree_iter_prev(__VA_ARGS__) #define splay_tree_iter_has_next(...) cdc_splay_tree_iter_has_next(__VA_ARGS__) #define splay_tree_iter_has_prev(...) cdc_splay_tree_iter_has_prev(__VA_ARGS__) #define splay_tree_iter_key(...) cdc_splay_tree_iter_key(__VA_ARGS__) #define splay_tree_iter_value(...) cdc_splay_tree_iter_value(__VA_ARGS__) #define splay_tree_iter_key_value(...) cdc_splay_tree_iter_key_value(__VA_ARGS__) #define splay_tree_iter_is_eq(...) cdc_splay_tree_iter_is_eq(__VA_ARGS__) #endif /** @} */ #endif // CDCONTAINERS_INCLUDE_CDCONTAINERS_SPLAY_TREE_H
maksimandrianov/cdstructures
src/tables/map-splay-tree.c
// The MIT License (MIT) // Copyright (c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "cdcontainers/splay-tree.h" #include "cdcontainers/tables/imap.h" #include <assert.h> #include <stdlib.h> static stat_t ctor(void **cntr, data_info_t *info) { assert(cntr != NULL); splay_tree_t **tree = (splay_tree_t **)cntr; return splay_tree_ctor(tree, info); } static stat_t ctorv(void **cntr, data_info_t *info, va_list args) { assert(cntr != NULL); splay_tree_t **tree = (splay_tree_t **)cntr; return splay_tree_ctorv(tree, info, args); } static void dtor(void *cntr) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_dtor(tree); } static stat_t get(void *cntr, void *key, void **value) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; return splay_tree_get(tree, key, value); } static size_t count(void *cntr, void *key) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; return splay_tree_count(tree, key); } static void find(void *cntr, void *key, void *it) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_iter_t *iter = (splay_tree_iter_t *)it; splay_tree_find(tree, key, iter); } static size_t size(void *cntr) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; return splay_tree_size(tree); } static bool empty(void *cntr) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; return splay_tree_empty(tree); } static void clear(void *cntr) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_clear(tree); } static stat_t insert(void *cntr, void *key, void *value, void *it, bool *inserted) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_insert1(tree, key, value, iter, inserted); } static stat_t insert_or_assign(void *cntr, void *key, void *value, void *it, bool *inserted) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_insert_or_assign1(tree, key, value, iter, inserted); } static size_t erase(void *cntr, void *key) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; return splay_tree_erase(tree, key); } static void swap(void *a, void *b) { assert(a != NULL); assert(b != NULL); splay_tree_t *ta = (splay_tree_t *)a; splay_tree_t *tb = (splay_tree_t *)b; splay_tree_swap(ta, tb); } static void begin(void *cntr, void *it) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_iter_t *iter = (splay_tree_iter_t *)it; splay_tree_begin(tree, iter); } static void end(void *cntr, void *it) { assert(cntr != NULL); splay_tree_t *tree = (splay_tree_t *)cntr; splay_tree_iter_t *iter = (splay_tree_iter_t *)it; splay_tree_end(tree, iter); } static void *iter_ctor() { return malloc(sizeof(splay_tree_iter_t)); } static void iter_dtor(void *it) { free(it); } static enum cdc_iterator_type type() { return CDC_BIDIR_ITERATOR; } static void iter_next(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; splay_tree_iter_next(iter); } static void iter_prev(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; splay_tree_iter_prev(iter); } static bool iter_has_next(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_iter_has_next(iter); } static bool iter_has_prev(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_iter_has_prev(iter); } static void *iter_key(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_iter_key(iter); } static void *iter_value(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_iter_value(iter); } static pair_t iter_key_value(void *it) { assert(it != NULL); splay_tree_iter_t *iter = (splay_tree_iter_t *)it; return splay_tree_iter_key_value(iter); } static bool iter_eq(void *it1, void *it2) { assert(it1 != NULL); assert(it2 != NULL); splay_tree_iter_t *iter1 = (splay_tree_iter_t *)it1; splay_tree_iter_t *iter2 = (splay_tree_iter_t *)it2; return splay_tree_iter_is_eq(iter1, iter2); } static const map_iter_table_t _iter_table = {.ctor = iter_ctor, .dtor = iter_dtor, .type = type, .next = iter_next, .prev = iter_prev, .has_next = iter_has_next, .has_prev = iter_has_prev, .key = iter_key, .value = iter_value, .key_value = iter_key_value, .eq = iter_eq}; static const map_table_t _table = {.ctor = ctor, .ctorv = ctorv, .dtor = dtor, .get = get, .count = count, .find = find, .size = size, .empty = empty, .clear = clear, .insert = insert, .insert_or_assign = insert_or_assign, .erase = erase, .swap = swap, .begin = begin, .end = end, .iter_table = &_iter_table}; const map_table_t *cdc_map_splay = &_table;
maksimandrianov/cdstructures
tests/test-stack.c
<filename>tests/test-stack.c // The MIT License (MIT) // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #define CDC_USE_SHORT_NAMES #include "test-common.h" #include "cdcontainers/adapters/stack.h" #include "cdcontainers/casts.h" #include <float.h> #include <stdarg.h> #include <CUnit/Basic.h> void test_stackv_ctor() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { cstack_t *s = NULL; CU_ASSERT_EQUAL(stack_ctor(tables[t], &s, NULL), CDC_STATUS_OK); CU_ASSERT(stack_empty(s)); stack_dtor(s); } } void test_stackv_ctorl() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 2, b = 3; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { cstack_t *s = NULL; CU_ASSERT_EQUAL(stack_ctorl(tables[t], &s, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(stack_size(s), 2); void *elem = stack_top(s); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); stack_pop(s); CU_ASSERT_EQUAL(stack_size(s), 1); elem = stack_top(s); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); stack_pop(s); CU_ASSERT(stack_empty(s)); stack_dtor(s); } } void test_stackv_push() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 0, b = 1, c = 2; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { cstack_t *s = NULL; CU_ASSERT_EQUAL(stack_ctor(tables[t], &s, NULL), CDC_STATUS_OK); stack_push(s, CDC_FROM_INT(a)); CU_ASSERT_EQUAL(stack_size(s), 1); void *elem = stack_top(s); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); stack_push(s, CDC_FROM_INT(b)); CU_ASSERT_EQUAL(stack_size(s), 2); elem = stack_top(s); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); stack_push(s, CDC_FROM_INT(c)); CU_ASSERT_EQUAL(stack_size(s), 3); elem = stack_top(s); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); stack_dtor(s); } } void test_stackv_pop() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 0, b = 1, c = 2, d = 3; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { cstack_t *s = NULL; CU_ASSERT_EQUAL(stack_ctorl(tables[t], &s, NULL, CDC_FROM_INT(a), CDC_FROM_INT(b), CDC_FROM_INT(c), CDC_FROM_INT(d), CDC_END), CDC_STATUS_OK); void *elem = stack_top(s); stack_pop(s); CU_ASSERT_EQUAL(stack_size(s), 3); CU_ASSERT_EQUAL(CDC_TO_INT(elem), d); elem = stack_top(s); stack_pop(s); CU_ASSERT_EQUAL(stack_size(s), 2); CU_ASSERT_EQUAL(CDC_TO_INT(elem), c); elem = stack_top(s); stack_pop(s); CU_ASSERT_EQUAL(stack_size(s), 1); CU_ASSERT_EQUAL(CDC_TO_INT(elem), b); elem = stack_top(s); stack_pop(s); CU_ASSERT(stack_empty(s)); CU_ASSERT_EQUAL(CDC_TO_INT(elem), a); stack_dtor(s); } } void test_stackv_swap() { const sequence_table_t *tables[] = {cdc_seq_carray, cdc_seq_array, cdc_seq_list}; int a = 2, b = 3, c = 4; for (size_t t = 0; t < CDC_ARRAY_SIZE(tables); ++t) { cstack_t *v = NULL; cstack_t *w = NULL; CU_ASSERT_EQUAL(stack_ctorl(tables[t], &v, NULL, CDC_FROM_INT(b), CDC_END), CDC_STATUS_OK); CU_ASSERT_EQUAL(stack_ctorl(tables[t], &w, NULL, CDC_FROM_INT(a), CDC_FROM_INT(c), CDC_END), CDC_STATUS_OK); stack_swap(v, w); CU_ASSERT_EQUAL(stack_size(v), 2); CU_ASSERT_EQUAL(CDC_TO_INT(stack_top(v)), c); CU_ASSERT_EQUAL(stack_size(w), 1); CU_ASSERT_EQUAL(CDC_TO_INT(stack_top(w)), b); stack_dtor(v); stack_dtor(w); } }
IvanKozlov95/ft_select
src/arg_print.c
<filename>src/arg_print.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* arg_print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/26 00:22:06 by ivankozlov #+# #+# */ /* Updated: 2019/06/26 21:07:10 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" #include "ft_printf.h" static bool is_selected(size_t idx, t_dlist *arg) { (void)idx; return (((t_arg *)arg->content)->selected); } static void print_selected_arg(t_dlist *arg, size_t idx, t_dlist *list) { static char *separator; (void)idx; (void)list; if (arg == NULL) { separator = ""; return ; } ft_printf("%s%s", separator, ((t_arg *)arg->content)->value); separator = " "; } void print_selected_args(t_dlist *args) { print_selected_arg(NULL, 0, NULL); dlstforeachif(args, print_selected_arg, is_selected); }
IvanKozlov95/ft_select
src/main.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/24 02:53:15 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 02:28:15 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" #include "ft_printf.h" static void print_usage(void) { ft_printf("usage: ./ft_select [argument ...]\n"); } static void main_loop(t_dlist **args) { t_info *info; info = get_set_info(); info->active_arg = *args; refresh_display_table(*args); while (1) { display_args(*args); user_input(args); if (*args == NULL) ft_select_stop(*args, false); } } int main(int ac, char *av[]) { t_dlist *args; if (ac < 2) print_usage(); else { init_config(); init_info(); args = argv_to_list(ac - 1, av + 1, arg_to_lst_elem); inti_signal_handlers(&args); main_loop(&args); ft_select_stop(args, false); } return (0); }
IvanKozlov95/ft_select
src/actions/search.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* search.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/28 02:07:03 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 03:26:40 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "keys.h" #include "dlist.h" #include "chars.h" #include "memory.h" #include "ftstring.h" #include "ft_select.h" static void match(t_dlist *arglist, size_t idx, t_dlist *list) { t_arg *arg; t_string *search; (void)idx; (void)list; search = get_set_info()->search; arg = (t_arg *)arglist->content; arg->search_match = ft_strstr(arg->value, search->content) == arg->value; } void ft_select_search(int c, t_dlist *args) { t_string *search; static char buf[2] = {0}; buf[0] = (char)c; search = get_set_info()->search; if (c < 0 && search->length > 0) { search->content[search->length - 1] = 0; search->length--; } else if (c > 0) string_append(search, buf); if (search->length > 0) dlstforeachif(args, match, NULL); } void ft_select_clear_search(int c) { if ((c != KBSPACE && !ISPRINT(c)) || ISSPACE(c)) { ft_bzero(get_set_info()->search->content, get_set_info()->search->length); get_set_info()->search->length = 0; } }
IvanKozlov95/ft_select
includes/ft_select.h
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_select.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/24 21:43:07 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 03:13:16 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FT_SELECT_H # define FT_SELECT_H # include "dlist.h" # include "output.h" # include "dstring.h" # include <term.h> # include <curses.h> # include <unistd.h> # include <stdbool.h> # include <termcap.h> # include <termios.h> # include <sys/ioctl.h> enum e_file_type { CFILE = 0, OFILE, HFILE, MAKEFILE, DOTFILE, DIR, EXECFILE, UNKNW, }; typedef enum e_file_type t_file_type; struct s_arg { t_file_type type; char *value; size_t length; bool selected; bool search_match; }; typedef struct s_arg t_arg; struct s_table { size_t rows; size_t cols; size_t col_width; }; typedef struct s_table t_table; struct s_info { struct termios attr; struct termios default_attr; t_table display_table; t_dlist *active_arg; t_string *search; }; typedef struct s_info t_info; typedef void (*t_move_action)(t_dlist *); /* ** src/info.c */ void init_info(void); void destroy_info(void); t_info *get_set_info(void); /* ** src/termconfig.c */ void init_config(void); void reset_config(void); /* ** src/error.c */ void fatal(const int exitcode, const char *fmt, ...); /* ** src/args.c */ t_dlist *argv_to_list(int ac, char *av[], t_dlist *(new_elem)(char *)); t_dlist *arg_to_lst_elem(char *arg); t_arg *get_longest_arg(t_dlist *args); /* ** src/display.c */ void display_args(t_dlist *args); void refresh_display_table(t_dlist *args); /* ** src/arg_print.c */ void print_selected_args(t_dlist *args); /* ** src/input.c */ void user_input(t_dlist **args); /* ** src/signal.c */ void inti_signal_handlers(t_dlist **args); /* ** src/actions/stop.c */ void ft_select_free_arg(void *arg, size_t size); void ft_select_stop(t_dlist *args, bool print_selected); /* ** src/actions/stop.c */ void move_active(int key_id, t_dlist *args); /* ** src/actions/search.c */ void ft_select_clear_search(int c); void ft_select_search(int c, t_dlist *args); /* ** MACROS */ # define EXIT_ERROR -1 # define _W struct winsize w # define _GETWINSIZE(w) ioctl(STDERR_FILENO, TIOCGWINSZ, &w) # define TERMWIDTH ({ _W; _GETWINSIZE(w); w.ws_col; }) # define TERMHEIGHT ({ _W; _GETWINSIZE(w); w.ws_row; }) # define SETTERMCMD(id) ({char *v = tgetstr(id, 0); tputs(v, 1, ft_putc_err);}) #endif
IvanKozlov95/ft_select
src/signal.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* signal.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/26 09:05:30 by ivankozlov #+# #+# */ /* Updated: 2019/06/26 10:27:37 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" #include <signal.h> static void ft_select_stop_signal(int signo, t_dlist **args) { static t_dlist **saved = NULL; if (signo == -1) saved = args; else ft_select_stop(*saved, false); } static void ft_select_suspend_signal(int signo) { (void)signo; reset_config(); signal(SIGTSTP, SIG_DFL); ioctl(STDOUT_FILENO, TIOCSTI, "\x1A"); } static void ft_select_continue_signal(int signo, t_dlist **args) { static t_dlist **saved = NULL; if (signo == -1) saved = args; else { init_config(); inti_signal_handlers(saved); display_args(*saved); } } static void ft_select_resize_signal(int signo, t_dlist **args) { static t_dlist **saved = NULL; saved = saved ? saved : args; if (signo == SIGWINCH) { refresh_display_table(*saved); display_args(*saved); } } void inti_signal_handlers(t_dlist **args) { signal(SIGINT, (void (*)(int))ft_select_stop_signal); signal(SIGABRT, (void (*)(int))ft_select_stop_signal); signal(SIGSTOP, (void (*)(int))ft_select_stop_signal); signal(SIGKILL, (void (*)(int))ft_select_stop_signal); signal(SIGQUIT, (void (*)(int))ft_select_stop_signal); signal(SIGWINCH, (void (*)(int))ft_select_resize_signal); signal(SIGTSTP, &ft_select_suspend_signal); signal(SIGCONT, (void (*)(int))ft_select_continue_signal); ft_select_stop_signal(-1, args); ft_select_resize_signal(-1, args); ft_select_continue_signal(-1, args); }
IvanKozlov95/ft_select
src/info.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* info.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/24 22:57:49 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 02:20:20 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "memory.h" #include "ft_select.h" t_info *get_set_info(void) { static t_info info; return (&info); } void init_info(void) { t_info *info; info = get_set_info(); info->search = string_init(0); } void destroy_info(void) { t_info *info; info = get_set_info(); string_destroy(info->search, FALSE); }
IvanKozlov95/ft_select
src/display.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/25 02:17:31 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 03:24:29 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "output.h" #include "colors.h" #include "ftstring.h" #include "ft_select.h" #include "ft_printf.h" #include "ftstring.h" static char *get_arg_highlight(t_arg *arg) { t_arg *selected_arg; selected_arg = get_set_info()->active_arg->content; if (arg->selected) return (UNDLINE""REVERSE); return (selected_arg == arg ? UNDLINE : ""); } static char *get_arg_color(t_arg *arg) { static char *colors[] = { MAG, CYN, BRBLU, YEL, GRN, BLU, RED, "", }; return (colors[arg->type]); } static void display_arg(t_dlist *arglist, size_t idx, t_dlist *list) { t_arg *arg; t_info *info; char *color; char *highlight; (void)list; arg = (t_arg *)arglist->content; info = get_set_info(); if (idx % info->display_table.cols == 0) ft_dprintf(STDERR_FILENO, "\n"); color = get_arg_color(arg); highlight = get_arg_highlight(arg); ft_dprintf(STDERR_FILENO, "%s%s", color, highlight); if (info->search->length > 0 && arg->search_match) ft_dprintf(STDERR_FILENO, BOLD"%s"RESET"%s%s%-*s"RESET, info->search->content, color, highlight, info->display_table.col_width - info->search->length, arg->value + info->search->length); else ft_dprintf(STDERR_FILENO, "%-*s%s", info->display_table.col_width, arg->value, RESET); } void refresh_display_table(t_dlist *args) { size_t tmp; t_info *info; info = get_set_info(); info->display_table.col_width = get_longest_arg(args)->length + 1; tmp = dlstcount(args); info->display_table.cols = TERMWIDTH / info->display_table.col_width; if (info->display_table.cols == 0) info->display_table.cols++; info->display_table.rows = tmp / info->display_table.cols + tmp % info->display_table.cols != 0; } void display_args(t_dlist *args) { t_info *info; info = get_set_info(); SETTERMCMD("cl"); if (info->search->length > 0) ft_dprintf(STDERR_FILENO, "search: %s\n", info->search->content); if (info->display_table.rows > TERMHEIGHT) return ; dlstforeachif(args, display_arg, NULL); }
IvanKozlov95/ft_select
src/actions/stop.c
<filename>src/actions/stop.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stop.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/26 00:33:05 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 02:27:53 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "memory.h" #include "ft_select.h" #include <stdlib.h> void ft_select_free_arg(void *arg, size_t size) { (void)size; ft_free(2, ((t_arg *)arg)->value, arg); } void ft_select_stop(t_dlist *args, bool print_selected) { reset_config(); destroy_info(); if (print_selected) print_selected_args(args); dlstdel(&args, ft_select_free_arg); exit(0); }
IvanKozlov95/ft_select
src/termconfig.c
<reponame>IvanKozlov95/ft_select /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* termconfig.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/24 22:54:21 by ivankozlov #+# #+# */ /* Updated: 2019/06/26 21:09:21 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "memory.h" #include "ft_select.h" #include <stdlib.h> #include <unistd.h> static void init_terminal_data(void) { int success; char *termtype; char buf[1024]; termtype = getenv("TERM"); if (termtype == NULL) fatal(EXIT_ERROR, "Specify a terminal type with\ `setenv TERM <yourtype>'.\n"); success = tgetent(buf, termtype); if (success < 0) fatal(EXIT_ERROR, "Could not access the termcap data base.\n"); if (success == 0) fatal(EXIT_ERROR, "Terminal type `%s' is not defined.\n", termtype); } void reset_config(void) { t_info *info; info = get_set_info(); tcsetattr(STDERR_FILENO, TCSANOW, &(info->default_attr)); SETTERMCMD("ve"); SETTERMCMD("te"); } void init_config(void) { t_info *info; init_terminal_data(); info = get_set_info(); tcgetattr(STDERR_FILENO, &(info->default_attr)); ft_memcpy(&(info->attr), &(info->default_attr), sizeof(struct termios)); info->attr.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDERR_FILENO, TCSANOW, &(info->attr)); SETTERMCMD("ti"); SETTERMCMD("vi"); }
IvanKozlov95/ft_select
src/input.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* input.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/25 21:03:18 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 03:26:21 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "keys.h" #include "chars.h" #include "ft_select.h" #include <unistd.h> static void select_arg(t_dlist *arglist, size_t idx, t_dlist *list) { t_arg *arg; (void)idx; (void)list; arg = (t_arg *)arglist->content; if (arg->search_match) arg->selected = true; } static void toggle_selected(t_dlist *args) { t_info *info; t_arg *active; info = get_set_info(); active = (t_arg *)info->active_arg->content; if (info->search->length == 0) active->selected = !active->selected; else dlstforeachif(args, select_arg, NULL); if (active->selected) info->active_arg = info->active_arg->next; if (info->active_arg == NULL) info->active_arg = args; } static void delete_active_arg(t_dlist **args) { t_dlist *next; t_dlist *active; active = get_set_info()->active_arg; next = active->next ? active->next : *args; dlstremove(args, active, ft_select_free_arg); get_set_info()->active_arg = next; } static void handle_bckspace(t_dlist **args) { if (get_set_info()->search->length > 0) return (ft_select_search(-1, NULL)); return (delete_active_arg(args)); } void user_input(t_dlist **args) { int c; c = 0; read(STDERR_FILENO, &c, 4); if (c == ' ') toggle_selected(*args); else if (c == KENTER) ft_select_stop(*args, true); else if (c == KESC) ft_select_stop(*args, false); else if (c == KBSPACE || c == KDELETE) handle_bckspace(args); else if (c == KUP || c == KDOWN || c == KLEFT || c == KRIGHT) move_active(c, *args); else if (ISPRINT(c)) ft_select_search(c, *args); ft_select_clear_search(c); }
IvanKozlov95/ft_select
src/actions/move.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/26 06:34:43 by ivankozlov #+# #+# */ /* Updated: 2019/06/26 21:05:40 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" static void left(t_dlist *args) { get_set_info()->active_arg = get_set_info()->active_arg->prev; if (!get_set_info()->active_arg) get_set_info()->active_arg = dlstlast(args); } static void right(t_dlist *args) { get_set_info()->active_arg = get_set_info()->active_arg->next; if (!get_set_info()->active_arg) get_set_info()->active_arg = args; } static void up(t_dlist *args) { size_t i; size_t cols; size_t count; t_dlist *active_arg; active_arg = get_set_info()->active_arg; i = dlstindexof(args, active_arg); count = dlstcount(args); cols = get_set_info()->display_table.cols; if (i < cols) cols = count % cols + cols * (i >= count % cols); while (cols-- > 0) left(args); } static void down(t_dlist *args) { size_t i; size_t cols; size_t count; t_dlist *active_arg; active_arg = get_set_info()->active_arg; i = dlstindexof(args, active_arg); count = dlstcount(args); cols = get_set_info()->display_table.cols; cols = i + cols < count ? cols : count - i + i % cols; while (cols-- > 0) right(args); } void move_active(int key_id, t_dlist *args) { static t_move_action dispatch[] = { 0, &left, 0, &up, 0, &right, 0, 0, 0, &down, }; (*dispatch[key_id % 10])(args); }
IvanKozlov95/ft_select
src/args.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ivankozlov <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/25 01:42:12 by ivankozlov #+# #+# */ /* Updated: 2019/06/28 03:37:13 by ivankozlov ### ########.fr */ /* */ /* ************************************************************************** */ #include "memory.h" #include "ftstring.h" #include "ft_select.h" #include <sys/stat.h> static t_file_type get_file_type(char *path) { char *name; t_file_type ret; struct stat f; ret = UNKNW; name = getfilename(path); if (lstat(path, &f)) ret = UNKNW; else if (S_ISDIR(f.st_mode)) ret = DIR; else if (f.st_mode & S_IXUSR) ret = EXECFILE; else if (strendswith(name, ".c")) ret = CFILE; else if (strendswith(name, ".o")) ret = OFILE; else if (strendswith(name, ".h")) ret = HFILE; else if (ft_strequ(name, "Makefile")) ret = MAKEFILE; else if (name[0] == '.') ret = DOTFILE; ft_free(1, name); return (ret); } t_arg *get_longest_arg(t_dlist *args) { t_arg *ret; t_arg *arg; ret = NULL; while (args) { arg = (t_arg *)args->content; if (ret == NULL || arg->length > ret->length) ret = arg; args = args->next; } return (ret); } t_dlist *arg_to_lst_elem(char *arg) { t_arg newarg; ft_bzero(&newarg, sizeof(t_arg)); newarg.value = ft_strdup(arg); newarg.length = ft_strlen(arg); newarg.type = get_file_type(arg); return (dlstnew(&newarg, sizeof(t_arg))); } t_dlist *argv_to_list(int ac, char *av[], t_dlist *(new_elem)(char *)) { int i; t_dlist *ret; i = -1; ret = NULL; while (++i < ac) DLIST_ADDCREATE(ret, new_elem(av[i])); return (ret); }
chuahou/wrtele
src/botapi.c
// SPDX-License-Identifier: ??? // Copyright (c) 2021 <NAME> #define _GNU_SOURCE #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <curl/curl.h> #include "botapi.h" #include "config.h" bool tele_send_message(char *msg) { CURL *curl; if ((curl = curl_easy_init())) { // Create the URL. char *url; if (asprintf(&url, "https://api.telegram.org/bot%s/sendMessage", config_tele_api_key()) < 0) { perror("Failed to create request URL"); curl_easy_cleanup(curl); return false; } // Encode message to catch special characters. char *encoded_msg = curl_easy_escape(curl, msg, 0); // Put fields in POST fields. char *postfields; if (asprintf(&postfields, "chat_id=%s&text=%s", config_tele_target_chat_id(), encoded_msg) < 0) { perror("Failed to create post fields"); curl_easy_cleanup(curl); return false; } curl_free(encoded_msg); // Perform CURL request. curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postfields); CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); free(url); free(postfields); if (res == CURLE_OK) { return true; } else { perror("CURL request error"); return false; } } perror("Failed to create CURL object"); return false; }
chuahou/wrtele
src/config.c
<filename>src/config.c // SPDX-License-Identifier: MIT // Copyright (c) 2021 <NAME> #include <ctype.h> #include <stdlib.h> #include <string.h> #include "config.h" #include "mac.h" char *config_tele_api_key() { return getenv("WRTELE_TELE_API_KEY"); } char *config_tele_target_chat_id() { return getenv("WRTELE_TELE_TARGET_CHAT_ID"); } struct device *config_mac_addrs(size_t *len) { // Make copy so we can strtok. char *env = getenv("WRTELE_MAC_ADDRS"); if (!env) return NULL; char *addrs = malloc(strlen(env) + 1); memcpy(addrs, env, strlen(env) + 1); // Iterate through tokens. *len = 0; struct device *devices = NULL; char *strtok_st; char *entry = strtok_r(addrs, ",;", &strtok_st); while (entry != NULL) { // Separate entry into MAC and device name. [mac]=[name] char *inner_strtok_st; char *mac = strtok_r(entry, "=", &inner_strtok_st); char *name = strtok_r(NULL, "=", &inner_strtok_st); if (!name) name = mac; // Use MAC as name if not provided. // Add new device. struct device *new_devices = realloc(devices, sizeof(struct device) * ++*len); if (!new_devices) { free(devices); len = 0; return NULL; } devices = new_devices; strncpy(devices[*len - 1].mac, mac, 17); devices[*len - 1].mac[17] = '\0'; strncpy(devices[*len - 1].name, name, MAX_DEVICE_NAME_LEN - 1); devices[*len - 1].name[MAX_DEVICE_NAME_LEN - 1] = '\0'; for (char *p = devices[*len - 1].mac; *p != '\0'; p++) *p = tolower(*p); devices[*len - 1].connected = false; // Advance to next token. entry = strtok_r(NULL, ",;", &strtok_st); } free(addrs); return devices; } char *config_list_command() { return getenv("WRTELE_LIST_COMMAND"); } unsigned int config_sleep_duration() { char *env = getenv("WRTELE_SLEEP_DURATION"); if (env) { long parse = strtol(env, NULL, 0); return parse <= 0L ? 1 : (unsigned int) parse; } else return 1; }
chuahou/wrtele
src/config.h
// SPDX-License-Identifier: MIT // Copyright (c) 2021 <NAME> // // Functions to access configuration. #ifndef __WRTELE_CONFIG_H_INCLUDED__ #define __WRTELE_CONFIG_H_INCLUDED__ #include "mac.h" // Get Telegram API key. Simple wrapper around getenv. char *config_tele_api_key(); // Get Telegram target chat ID. Simple wrapper around getenv. char *config_tele_target_chat_id(); // MAC addresses to watch, separated by any of " ,;", in all lowercase. Length // of array returned in len. struct device *config_mac_addrs(size_t *len); // Command(s) to execute to list MAC addresses, separated by ';'. char *config_list_command(); // Duration to sleep between checks. unsigned int config_sleep_duration(); #endif