add util.h and util.c

This commit is contained in:
Akos Horvath 2023-05-26 16:45:49 +02:00
parent 9bb7c645aa
commit 60829dd1c1
2 changed files with 134 additions and 0 deletions

81
util.c Normal file
View File

@ -0,0 +1,81 @@
#include "util.h"
#include <string.h>
#include <assert.h>
void wm_treenode_init(TreeNode *node, NodeType type, TreeNode *parent)
{
assert(node);
node->parent = parent;
node->type = type;
node->children = (NodeArray) {0};
wm_nodearray_init(&node->children);
}
void wm_nodearray_init(NodeArray *arr)
{
assert(arr);
arr->capacity = 10;
arr->nodes = calloc(arr->capacity, sizeof(TreeNode));
arr->size = 0;
}
void wm_nodearray_push(NodeArray *arr, TreeNode node)
{
assert(arr);
arr->size++;
if (arr->size >= arr->capacity) {
TreeNode* temp = calloc(arr->capacity, sizeof(TreeNode));
memcpy(temp, arr->nodes, arr->capacity * sizeof(TreeNode));
free(arr->nodes);
size_t old_capacity = arr->capacity;
arr->capacity = old_capacity * 2;
arr->nodes = calloc(arr->capacity, sizeof(TreeNode));
memcpy(arr->nodes, temp, old_capacity);
free(temp);
arr->nodes[arr->size - 1] = node;
return;
}
arr->nodes[arr->size - 1] = node;
}
bool wm_nodearray_pop(NodeArray *arr, TreeNode *ret)
{
assert(arr);
if (!ret || !arr)
return false;
if (arr->size == 0)
return false;
*ret = arr->nodes[arr->size - 1];
arr->size--;
return true;
}
bool wm_nodearray_remove(NodeArray *arr, size_t index)
{
assert(arr);
if (!arr)
return false;
if (index >= arr->size)
return false;
if (index == arr->size - 1) {
arr->size--;
return true;
}
memmove(arr->nodes + index, arr->nodes + index+1, arr->size-1 * sizeof(TreeNode));
return true;
}

53
util.h Normal file
View File

@ -0,0 +1,53 @@
#ifndef UTIL_H
#define UTIL_H
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define WM_VERT_LEFT 0
#define WM_VERT_RIGHT 1
#define WM_HORIZ_TOP 0
#define WM_HORIZ_BOT 1
typedef enum NodeType {
VERTICAL,
HORIZONTAL,
TAB,
CLIENT,
COUNT
} NodeType;
typedef struct TreeNode TreeNode;
typedef struct NodeArray NodeArray;
typedef struct Client Client;
struct NodeArray {
TreeNode *nodes;
size_t size;
size_t capacity;
};
struct TreeNode {
NodeType type;
TreeNode *parent;
NodeArray children;
int x;
int y;
int w;
int h;
Client *client;
};
void wm_treenode_init(TreeNode *node, NodeType type, TreeNode *parent);
void wm_nodearray_init(NodeArray *arr);
void wm_nodearray_push(NodeArray *arr, TreeNode node);
bool wm_nodearray_pop(NodeArray *arr, TreeNode *ret);
bool wm_nodearray_remove(NodeArray *arr, size_t index);
#endif