songvec.c 2.41 KB
Newer Older
1
#include "songvec.h"
2
#include "song.h"
3 4
#include "utils.h"

5 6 7
#include <assert.h>
#include <string.h>

8 9
static pthread_mutex_t nr_lock = PTHREAD_MUTEX_INITIALIZER;

10 11 12
/* Only used for sorting/searchin a songvec, not general purpose compares */
static int songvec_cmp(const void *s1, const void *s2)
{
13 14
	const struct song *a = ((const struct song * const *)s1)[0];
	const struct song *b = ((const struct song * const *)s2)[0];
15 16 17
	return strcmp(a->url, b->url);
}

18
static size_t sv_size(const struct songvec *sv)
19
{
20
	return sv->nr * sizeof(struct song *);
21 22 23 24
}

void songvec_sort(struct songvec *sv)
{
25
	pthread_mutex_lock(&nr_lock);
26
	qsort(sv->base, sv->nr, sizeof(struct song *), songvec_cmp);
27
	pthread_mutex_unlock(&nr_lock);
28 29
}

30
struct song *
31
songvec_find(const struct songvec *sv, const char *url)
32 33
{
	int i;
34
	struct song *ret = NULL;
35

36 37 38 39 40 41 42 43 44
	pthread_mutex_lock(&nr_lock);
	for (i = sv->nr; --i >= 0; ) {
		if (strcmp(sv->base[i]->url, url))
			continue;
		ret = sv->base[i];
		break;
	}
	pthread_mutex_unlock(&nr_lock);
	return ret;
45 46
}

47 48
int
songvec_delete(struct songvec *sv, const struct song *del)
49
{
50
	size_t i;
51

52
	pthread_mutex_lock(&nr_lock);
53
	for (i = 0; i < sv->nr; ++i) {
54 55
		if (sv->base[i] != del)
			continue;
56
		/* we _don't_ call song_free() here */
57 58 59 60 61
		if (!--sv->nr) {
			free(sv->base);
			sv->base = NULL;
		} else {
			memmove(&sv->base[i], &sv->base[i + 1],
62
				(sv->nr - i) * sizeof(struct song *));
63 64
			sv->base = xrealloc(sv->base, sv_size(sv));
		}
65 66
		pthread_mutex_unlock(&nr_lock);
		return i;
67
	}
68
	pthread_mutex_unlock(&nr_lock);
69

70
	return -1; /* not found */
71 72
}

73 74
void
songvec_add(struct songvec *sv, struct song *add)
75
{
76
	pthread_mutex_lock(&nr_lock);
77 78 79
	++sv->nr;
	sv->base = xrealloc(sv->base, sv_size(sv));
	sv->base[sv->nr - 1] = add;
80
	pthread_mutex_unlock(&nr_lock);
81 82
}

83
void songvec_destroy(struct songvec *sv)
84
{
85
	pthread_mutex_lock(&nr_lock);
86 87
	sv->nr = 0;
	pthread_mutex_unlock(&nr_lock);
Eric Wong's avatar
Eric Wong committed
88 89 90 91
	if (sv->base) {
		free(sv->base);
		sv->base = NULL;
	}
92
}
93

94 95
int
songvec_for_each(const struct songvec *sv,
96
		 int (*fn)(struct song *, void *), void *arg)
97
{
98
	size_t i;
99
	size_t prev_nr;
100

101
	pthread_mutex_lock(&nr_lock);
102
	for (i = 0; i < sv->nr; ) {
103
		struct song *song = sv->base[i];
104 105 106 107

		assert(song);
		assert(*song->url);

108
		prev_nr = sv->nr;
109 110
		pthread_mutex_unlock(&nr_lock); /* fn() may block */
		if (fn(song, arg) < 0)
111
			return -1;
112
		pthread_mutex_lock(&nr_lock); /* sv->nr may change in fn() */
113 114
		if (prev_nr == sv->nr)
			++i;
115
	}
116
	pthread_mutex_unlock(&nr_lock);
117 118 119

	return 0;
}