summaryrefslogtreecommitdiffstats
path: root/src/stringlist.c
blob: 96762a18a67a07f42e622936b169627f4d4b5aea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "stringlist.h"

struct StringList
{
	char **list;
	unsigned int count;
};

StringList* stringListCreate(size_t len)
{
	StringList *ret = malloc(sizeof(StringList));
	ret->count = len;
	ret->list = malloc(sizeof(char*) * len);

	return ret;
}

int stringListInsertAt(StringList *l, unsigned int pos, char *str)
{
	if(!l || !l->list || l->count < pos)
		return 0;
	
	l->list[pos] = str;

	return 1;
}

unsigned int stringListCount(StringList *l)
{
	if (!l)
		return 0;
	return l->count;
}

char* stringListGetAt(StringList *l, unsigned int pos)
{
	if (!l || !l->list || pos >= l->count)
		return NULL;
	
	return l->list[pos];
}

StringList* listToCList(PyObject* list)
{
	if (!list || !PyList_Check(list))
		return NULL;

	unsigned int len = PyList_Size(list);
	StringList *ret = malloc(sizeof(StringList));
	ret->count = len;
	ret->list = malloc(sizeof(char*) * len);

	for (unsigned int i = 0; i < len; i++)
	{
		PyObject *elem = PyList_GetItem(list, i);
		ret->list[i] = malloc(sizeof(char) * (PyBytes_Size(elem) + 1));
		strcpy(ret->list[i], PyBytes_AsString(elem));
	}

	return ret;
}

PyObject* cListToPyList(StringList* list)
{
	if (!list)
		Py_RETURN_NONE;

	PyObject *ret = PyList_New(list->count);
	for(unsigned int i = 0; i < list->count; i++)
	{
		PyList_SetItem(ret, i, PyBytes_FromString(list->list[i]));
	}

	return ret;
}

void stringListPrint(StringList* list)
{
	if (!list)
		return;

	for(unsigned int i = 0; i < list->count; i++)
	{
		printf("\"%s\"", list->list[i]);
		if (i < list->count - 1)
			printf(", ");
	}
}

void stringListFree(StringList* list)
{
	if (!list)
		return;

	if (list && list->list)
	{
		for(unsigned int i = 0; i < list->count; i++)
		{
			free(list->list[i]);
		}

		free(list->list);
	}

	if (list)
		free(list);
}