+static unsigned headerhash(struct bytestring name)
+{
+ /*
+ * This is stolen from hash_string() in ccan/hash, but adapted
+ * to add the xtolower() call and use a bytestring
+ */
+ unsigned ret = 0;
+ size_t i;
+
+ for (i = 0; i < name.len; i++)
+ ret = (ret << 5) - ret + xtolower(name.ptr[i]);
+
+ return ret % INDEX_HASH_SIZE;
+}
+
+static struct rfc822_headers_of_name *headers_of_name(struct rfc822_msg *msg,
+ struct bytestring name)
+{
+ unsigned hash = headerhash(name);
+ struct rfc822_headers_of_name *hn;
+
+ list_for_each(&msg->header_index[hash], hn, bucket) {
+ if (hdr_name_eq(hn->name, name))
+ return hn;
+ }
+
+ return NULL;
+}
+
+static struct rfc822_header *index_header(struct rfc822_msg *msg,
+ struct rfc822_header *hdr)
+{
+ struct bytestring hname = rfc822_header_raw_name(msg, hdr);
+ struct rfc822_headers_of_name *hn = headers_of_name(msg, hname);
+
+ if (!hn) {
+ unsigned hash = headerhash(hname);
+
+ hn = talz(msg, struct rfc822_headers_of_name);
+ ALLOC_CHECK(hn, NULL);
+
+ hn->name = hname;
+ hn->first = NULL;
+ hn->lastptr = &hn->first;
+ list_add_tail(&msg->header_index[hash], &hn->bucket);
+ }
+
+ hdr->name_next = NULL;
+ *(hn->lastptr) = hdr;
+ hn->lastptr = &hdr->name_next;
+ return hdr;
+}
+
+struct rfc822_header *rfc822_first_header_of_name(struct rfc822_msg *msg,
+ const char *name)
+{
+ struct bytestring namebs = bytestring_from_string(name);
+ struct rfc822_headers_of_name *hn = headers_of_name(msg, namebs);
+ struct rfc822_header *hdr;
+
+ if (hn)
+ return hn->first;
+
+ do {
+ hdr = next_header_parse(msg);
+ if (hdr && rfc822_header_is(msg, hdr, name))
+ return hdr;
+ } while (hdr);
+
+ return NULL;
+}
+