+static mailbox_t *new_mailbox (void *ctx, const char *name, const char *addr)
+{
+ mailbox_t *mailbox;
+
+ mailbox = talloc (ctx, mailbox_t);
+ if (! mailbox)
+ return NULL;
+
+ mailbox->name = talloc_strdup (mailbox, name);
+ mailbox->addr = talloc_strdup (mailbox, addr);
+ mailbox->count = 1;
+
+ return mailbox;
+}
+
+static int mailbox_compare (const void *v1, const void *v2)
+{
+ const mailbox_t *m1 = v1, *m2 = v2;
+ int ret;
+
+ ret = strcmp_null (m1->name, m2->name);
+ if (! ret)
+ ret = strcmp (m1->addr, m2->addr);
+
+ return ret;
+}
+
+/* Returns true iff name and addr is duplicate. If not, stores the
+ * name/addr pair in order to detect subsequent duplicates. */
+static bool
+is_duplicate (const search_context_t *ctx, const char *name, const char *addr)
+{
+ char *key;
+ GList *list, *l;
+ mailbox_t *mailbox;
+
+ list = g_hash_table_lookup (ctx->addresses, addr);
+ if (list) {
+ mailbox_t find = {
+ .name = name,
+ .addr = addr,
+ };
+
+ l = g_list_find_custom (list, &find, mailbox_compare);
+ if (l) {
+ mailbox = l->data;
+ mailbox->count++;
+ return true;
+ }
+
+ mailbox = new_mailbox (ctx->format, name, addr);
+ if (! mailbox)
+ return false;
+
+ /*
+ * XXX: It would be more efficient to prepend to the list, but
+ * then we'd have to store the changed list head back to the
+ * hash table. This check is here just to avoid the compiler
+ * warning for unused result.
+ */
+ if (list != g_list_append (list, mailbox))
+ INTERNAL_ERROR ("appending to list changed list head\n");
+
+ return false;
+ }
+
+ key = talloc_strdup (ctx->format, addr);
+ if (! key)
+ return false;
+
+ mailbox = new_mailbox (ctx->format, name, addr);
+ if (! mailbox)
+ return false;
+
+ list = g_list_append (NULL, mailbox);
+ if (! list)
+ return false;
+
+ g_hash_table_insert (ctx->addresses, key, list);
+
+ return false;
+}
+