On 18. 11. 2026 09:59, Ruediger Pluem via dev wrote:

On 11/16/26 4:10 PM, Yann Ylavic wrote:
On Mon, Nov 16, 2026 at 3:19 PM Rainer Jung<[email protected]> wrote:
Can't we delay apr_uri_port_of_scheme() until we know there is no ":port" still?
Due to the use of goto, the code jumps a bit back and forth. So I found
it more robust to set immediately a default port when the scheme is
found and then overwrite it when a specific port is found than to find
all the exit points after (not necessarily below) the port detection and
then fall back to the default.
Looks like the below does it (full patch not cumulative, claude confirms).
My concern is that apr_uri_port_of_scheme() is quite slow, though the
common case is probably the one added here..

diff -ru a/uri/apr_uri.c b/uri/apr_uri.c
--- a/uri/apr_uri.c 2026-11-16 16:02:56.759516227 +0100
+++ b/uri/apr_uri.c 2026-11-16 16:02:56.784734796 +0100
@@ -999,6 +999,7 @@
              if (have_zone_id) {
                  percent_decode_scope_zone_id(uptr->hostname);
              }
+            uptr->port = apr_uri_port_of_scheme(uptr->scheme);
              goto deal_with_path;
          }
          uptr->hostname = apr_pstrmemdup(p,
Sounds sensible. Maybe AI can help us generate all the test cases such that
we can be sure it works and keeps working after changes.

I have an implementation ready that uses a generated minimal perfect hash function for lookups. The hash function is O(strlen(key)) to calculate the hash of the lookup key and O(1) to find the scheme. Except for the very first scheme in in the list, where linear lookup needs just a single strcasecmp(), it's faster by up to 5 times from the current lookup.

I thought of using gperf to generate the hash function, but then decided on using a Python module. The patch is attached, along with some basic performance measurement results.

-- Brane
Index: Makefile.in
===================================================================
--- Makefile.in (revision 1940368)
+++ Makefile.in (working copy)
@@ -131,6 +131,9 @@
 
 encoding/apr_escape.lo: include/private/apr_escape_test_char.h 
 
+# Included generated perfect hash function
+uri/apr_uri.lo: uri/uri_schemes.h uri/uri_schemes_perfect_hash.inc
+
 install-modules: install-modules-@APR_HAVE_MODULES@
 
 install-modules-no:
Index: build/perfect-hash/generate.py
===================================================================
--- build/perfect-hash/generate.py      (nonexistent)
+++ build/perfect-hash/generate.py      (working copy)
@@ -0,0 +1,82 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import re
+import sys
+import tempfile
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import IO, Iterable
+
+import perfect_hash
+
+HERE = Path(__file__).resolve(strict=True).parent
+ROOT = HERE.parent.parent
+
+
+@dataclass(kw_only=True, frozen=True)
+class Generator:
+    template: Path
+    output: Path
+    options: Iterable[str]
+    write_keys: Callable[[IO[str]], None]
+
+
+def _gen_apr_uri_schemes(output: IO[str]) -> None:
+    """
+    Generate the list of known URI scheme names as defined in uri/apr_uri.c.
+    The generated list of keys MUST be in the same order as in the source.
+    """
+    rx = re.compile(
+        r'^\s+\{\s*"(?P<scheme>[^"]+)",\s*APR_URI_[A-Z]+_DEFAULT_PORT\s*\}')
+    with open(ROOT / "uri" / "apr_uri.c") as input:
+        for line in input.readlines():
+            if (m := rx.match(line)) is not None:
+                output.write(f"{m.group('scheme')}\n")
+
+
+GENERATORS = {
+    "apr-uri-schemes": Generator(
+        template=HERE / "uri_schemes_perfect_hash.tmpl",
+        output=ROOT / "uri" / "uri_schemes_perfect_hash.inc",
+        options=["--indent=8"],
+        write_keys=_gen_apr_uri_schemes)
+}
+
+
+def main() -> None:
+    if len(sys.argv) != 2:
+        print(f"Usage: {HERE.name} <generator>", file=sys.stderr)
+        sys.exit(1)
+
+    generator = GENERATORS.get(sys.argv[1])
+    if generator is None:
+        print(f"Unknown generator »{sys.argv[1]}«", file=sys.stderr)
+        sys.exit(1)
+
+    with tempfile.NamedTemporaryFile(mode="w+t", delete=True, dir=HERE) as kf:
+        generator.write_keys(kf.file)
+        kf.flush()
+        sys.argv = ["perfect-hash",
+                    kf.name, str(generator.template),
+                    "-v", *generator.options,
+                    "-o", str(generator.output)]
+        perfect_hash.main()
+
+
+if __name__ == "__main__":
+    main()
Index: build/perfect-hash/pyproject.toml
===================================================================
--- build/perfect-hash/pyproject.toml   (nonexistent)
+++ build/perfect-hash/pyproject.toml   (working copy)
@@ -0,0 +1,40 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+[project]
+name = "minimal-perfect-hash"
+version = "1.0.0"
+license = "Apache-2"
+requires-python = ">=3.8"
+
+dependencies = [
+    "perfect-hash",
+]
+
+[dependency-groups]
+dev = [
+    "pyright",
+    "ruff",
+]
+
+[tool.pyright]
+pythonVersion = "3.8"
+
+[tool.ruff]
+src = ["."]
+target-version = "py38"
+
+[tool.ruff.lint]
+select = ["E", "F", "I", "B", "Q", "UP"]
Index: build/perfect-hash/uri_schemes_perfect_hash.tmpl
===================================================================
--- build/perfect-hash/uri_schemes_perfect_hash.tmpl    (nonexistent)
+++ build/perfect-hash/uri_schemes_perfect_hash.tmpl    (working copy)
@@ -0,0 +1,50 @@
+/* -*- c -*-
+ * GENERATED FILE -- DO NOT EDIT -- To regenerate:
+ *
+ *    cd .../build/perfect-hash
+ *    uv sync
+ *    uv run ./generate.py apr-uri-schemes
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+static const int num_uri_schemes = $NK;
+
+static int get_uri_scheme_index(const char *scheme_str)
+{
+    const int graph_size = $NG;
+    const int graph[] = {
+        $G
+    };
+
+    const int salt_size = $NS;
+    const char salt_1[] = "$S1";
+    const char salt_2[] = "$S2";
+
+    unsigned char c;
+    int f1 = 0, f2 = 0, i;
+
+    for (i = 0; (c = apr_tolower(scheme_str[i])) && i < salt_size; ++i) {
+        f1 += salt_1[i] * c;
+        f2 += salt_2[i] * c;
+    }
+    i = (graph[f1 % graph_size] + graph[f2 % graph_size]) % graph_size;
+    if (i < num_uri_schemes && 0 == strcasecmp(scheme_str, schemes[i].name))
+        return i;
+
+    return -1;
+}
Index: test/testuri.c
===================================================================
--- test/testuri.c      (revision 1940368)
+++ test/testuri.c      (working copy)
@@ -19,9 +19,12 @@
 
 #include "testutil.h"
 #include "apr_general.h"
+#include "apr_lib.h"
 #include "apr_strings.h"
 #include "apr_uri.h"
 
+#include "../uri/uri_schemes.h"
+
 struct aup_test {
     const char *uri;
     apr_status_t rv;
@@ -339,6 +342,47 @@
     }
 }
 
+
+static const schemes_t *schemes;
+
+#include "../uri/uri_schemes_perfect_hash.inc"
+
+static void test_uri_schemes_perfect_hash(abts_case *tc, void *data)
+{
+    int i;
+    int http = -1, ssh = -1;
+
+    schemes = apr__uri_schemes;
+    for (i = 0; schemes[i].name; ++i) {
+        const char *const name = schemes[i].name;
+
+        ABTS_INT_EQUAL(tc, get_uri_scheme_index(name), i);
+        if (0 == strcmp(name, "http"))
+            http = i;
+        else if (0 == strcmp(name, "ssh"))
+            ssh = i;
+    }
+    ABTS_INT_EQUAL(tc, i, num_uri_schemes);
+
+    ABTS_INT_NEQUAL(tc, http, -1);
+    ABTS_INT_EQUAL(tc, get_uri_scheme_index("HTTP"), http);
+    ABTS_INT_NEQUAL(tc, ssh, -1);
+    ABTS_INT_EQUAL(tc, get_uri_scheme_index("sSh"), ssh);
+}
+
+static void test_port_of_scheme(abts_case *tc, void *data)
+{
+    const schemes_t *s;
+
+    ABTS_INT_EQUAL(tc, apr_uri_port_of_scheme(NULL), 0);
+    ABTS_INT_EQUAL(tc, apr_uri_port_of_scheme(""), 0);
+
+    for (s = apr__uri_schemes; s->name; ++s) {
+        ABTS_INT_EQUAL(tc, apr_uri_port_of_scheme(s->name), s->default_port);
+    }
+}
+
+
 abts_suite *testuri(abts_suite *suite)
 {
     suite = ADD_SUITE(suite);
@@ -345,7 +389,8 @@
 
     abts_run_test(suite, test_aup, NULL);
     abts_run_test(suite, test_uph, NULL);
+    abts_run_test(suite, test_uri_schemes_perfect_hash, NULL);
+    abts_run_test(suite, test_port_of_scheme, NULL);
 
     return suite;
 }
-
Index: uri/apr_uri.c
===================================================================
--- uri/apr_uri.c       (revision 1940368)
+++ uri/apr_uri.c       (working copy)
@@ -23,6 +23,7 @@
 
 #include "apu.h"
 #include "apr.h"
+#include "apr_lib.h"  /* The perfect hash function uses apr_tolower(). */
 #include "apr_general.h"
 #include "apr_strings.h"
 
@@ -31,21 +32,14 @@
 
 #include "apr_uri.h"
 
-typedef struct schemes_t schemes_t;
+#include "uri_schemes.h"
 
-/** Structure to store various schemes and their default ports */
-struct schemes_t {
-    /** The name of the scheme */
-    const char *name;
-    /** The default port for the scheme */
-    apr_port_t default_port;
-};
-
 /* Some WWW schemes and their default ports; this is basically /etc/services */
 /* This will become global when the protocol abstraction comes */
-/* As the schemes are searched by a linear search, */
-/* they are sorted by their expected frequency */
-static schemes_t schemes[] =
+/* Schemes are searched by a perfect hash function, order doesn't matter.
+   Scheme names are case-insensitive and must be defined here in lower case.
+   Regenerate 'uri_schemes_perfect_hash.inc' every time this list changes. */
+static const schemes_t schemes[] =
 {
     {"http",     APR_URI_HTTP_DEFAULT_PORT},
     {"ftp",      APR_URI_FTP_DEFAULT_PORT},
@@ -69,6 +63,8 @@
     {"ssh",      APR_URI_SSH_DEFAULT_PORT},
     { NULL, 0xFFFF }     /* unknown port */
 };
+#define NUM_SCHEMES (sizeof(schemes) / sizeof(schemes[0]) - 1)
+const schemes_t *const apr__uri_schemes = schemes;  /* used by tests */
 
 #define LINK_LOCAL(ipv6addr) ((strlen(ipv6addr) >= 5) && \
                              ((ipv6addr)[4] == ':') && \
@@ -171,16 +167,14 @@
     return hostcopy;
 }
 
+#include "uri_schemes_perfect_hash.inc"
+
 APR_DECLARE(apr_port_t) apr_uri_port_of_scheme(const char *scheme_str)
 {
-    schemes_t *scheme;
-
     if (scheme_str) {
-        for (scheme = schemes; scheme->name != NULL; ++scheme) {
-            if (strcasecmp(scheme_str, scheme->name) == 0) {
-                return scheme->default_port;
-            }
-        }
+        const int index = get_uri_scheme_index(scheme_str);
+        if (0 <= index && index < NUM_SCHEMES)
+            return schemes[index].default_port;
     }
     return 0;
 }
Index: uri/uri_schemes.h
===================================================================
--- uri/uri_schemes.h   (nonexistent)
+++ uri/uri_schemes.h   (working copy)
@@ -0,0 +1,27 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+typedef struct schemes_t schemes_t;
+
+/** Structure to store various schemes and their default ports */
+struct schemes_t {
+    /** The name of the scheme */
+    const char *name;
+    /** The default port for the scheme */
+    apr_port_t default_port;
+};
+
+extern const schemes_t *const apr__uri_schemes;
Index: uri/uri_schemes_perfect_hash.inc
===================================================================
--- uri/uri_schemes_perfect_hash.inc    (nonexistent)
+++ uri/uri_schemes_perfect_hash.inc    (working copy)
@@ -0,0 +1,51 @@
+/* -*- c -*-
+ * GENERATED FILE -- DO NOT EDIT -- To regenerate:
+ *
+ *    cd .../build/perfect-hash
+ *    uv sync
+ *    uv run ./generate.py apr-uri-schemes
+ */
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+static const int num_uri_schemes = 20;
+
+static int get_uri_scheme_index(const char *scheme_str)
+{
+    const int graph_size = 22;
+    const int graph[] = {
+        0, 21, 1, 4, 7, 10, 5, 8, 0, 18, 20, 8, 5, 2, 5, 11, 
+        20, 11, 7, 1, 0, 9
+    };
+
+    const int salt_size = 8;
+    const char salt_1[] = "2yf5zDla";
+    const char salt_2[] = "L0APWi71";
+
+    unsigned char c;
+    int f1 = 0, f2 = 0, i;
+
+    for (i = 0; (c = apr_tolower(scheme_str[i])) && i < salt_size; ++i) {
+        f1 += salt_1[i] * c;
+        f2 += salt_2[i] * c;
+    }
+    i = (graph[f1 % graph_size] + graph[f2 % graph_size]) % graph_size;
+    if (i < num_uri_schemes && 0 == strcasecmp(scheme_str, schemes[i].name))
+        return i;
+
+    return -1;
+}
#include <assert.h>
#include <apr_uri.h>

const int repeat = 100 * 1000 * 1000;
const char scheme[] = "http";
const int default_port = APR_URI_HTTP_DEFAULT_PORT;

int main(void)
{
    int i;

    assert(apr_uri_port_of_scheme(scheme) == default_port);
    for (i = 0; i < repeat; ++i)
        apr_uri_port_of_scheme(scheme);
}

<<attachment: bench-apr-uri-port-of-scheme.zip>>

Reply via email to