Rename this for consistency.
[beanstalkd.git] / tube.c
blob86de1d96eb5e17f9d2252290fffaa4b557701252
1 /* tube.c - tubes implementation */
3 /* Copyright (C) 2008 Keith Rarick and Philotic Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include <stdlib.h>
20 #include <string.h>
22 #include "ms.h"
23 #include "stat.h"
24 #include "tube.h"
25 #include "prot.h"
26 #include "util.h"
28 struct ms tubes;
30 tube
31 make_tube(const char *name)
33 tube t;
35 t = malloc(sizeof(struct tube));
36 if (!t) return NULL;
38 t->refs = 0;
40 t->name[MAX_TUBE_NAME_LEN - 1] = '\0';
41 strncpy(t->name, name, MAX_TUBE_NAME_LEN - 1);
42 if (t->name[MAX_TUBE_NAME_LEN - 1] != '\0') twarnx("truncating tube name");
44 pq_init(&t->ready, job_pri_cmp);
45 pq_init(&t->delay, job_delay_cmp);
46 t->buried = (struct job) { &t->buried, &t->buried, 0 };
47 ms_init(&t->waiting, NULL, NULL);
49 t->stat = (struct stats) {0, 0, 0, 0};
50 t->using_ct = t->watching_ct = 0;
52 return t;
55 static void
56 tube_free(tube t)
58 prot_remove_tube(t);
59 pq_clear(&t->ready);
60 ms_clear(&t->waiting);
61 free(t);
64 void
65 tube_dref(tube t)
67 if (!t) return;
68 if (t->refs < 1) return twarnx("refs is zero for tube: %s", t->name);
70 --t->refs;
71 if (t->refs < 1) tube_free(t);
74 void
75 tube_iref(tube t)
77 if (!t) return;
78 ++t->refs;
81 static tube
82 make_and_insert_tube(const char *name)
84 int r;
85 tube t = NULL;
87 t = make_tube(name);
88 if (!t) return NULL;
90 /* We want this global tube list to behave like "weak" refs, so don't
91 * increment the ref count. */
92 r = ms_append(&tubes, t);
93 if (!r) return tube_dref(t), NULL;
95 return t;
98 tube
99 tube_find(const char *name)
101 tube t;
102 size_t i;
104 for (i = 0; i < tubes.used; i++) {
105 t = tubes.items[i];
106 if (strncmp(t->name, name, MAX_TUBE_NAME_LEN) == 0) return t;
108 return NULL;
111 tube
112 tube_find_or_make(const char *name)
114 return tube_find(name) ? : make_and_insert_tube(name);