How does http::uri::Authority::from_static provide compile-time validation for static authority strings?

Authority::from_static is a const function that parses a static &'static str into an Authority at compile time, rejecting invalid authorities with a compile-time error or panic in const context. This eliminates runtime parsing overhead and ensures invalid authority strings never reach production code, since invalid inputs cause compilation failure rather than runtime errors.

Basic Usage of from_static

use http::uri::Authority;
 
fn basic_usage() {
    // from_static takes a static string and parses it at compile time
    let authority: Authority = Authority::from_static("example.com");
    
    // The authority is validated during compilation
    // No runtime parsing occurs
    
    // Access the authority as a string
    assert_eq!(authority.as_str(), "example.com");
    
    // Works with ports
    let with_port = Authority::from_static("example.com:8080");
    assert_eq!(with_port.as_str(), "example.com:8080");
    
    // Works with host and port
    let host_port = Authority::from_static("localhost:3000");
    assert_eq!(host_port.as_str(), "localhost:3000");
}

from_static takes a string literal and returns a validated Authority.

Compile-Time Validation

use http::uri::Authority;
 
fn compile_time_validation() {
    // Valid authorities compile successfully:
    let _a = Authority::from_static("example.com");
    let _b = Authority::from_static("example.com:443");
    let _c = Authority::from_static("localhost:8080");
    let _d = Authority::from_static("127.0.0.1:8080");
    let _e = Authority::from_static("[::1]:8080");  // IPv6
    
    // Invalid authorities would fail to compile:
    // Authority::from_static("example.com:99999");  // Port out of range
    // Authority::from_static("exam:ple.com");       // Invalid characters
    // Authority::from_static("");                   // Empty authority
    // Authority::from_static(":8080");               // No host
    
    // The validation happens during compilation
    // No runtime parsing cost
}

Invalid authorities cause compilation errors, catching mistakes early.

Const Context and Const Evaluation

use http::uri::Authority;
 
// from_static is a const fn, usable in const context
const MY_AUTHORITY: Authority = Authority::from_static("api.example.com:443");
 
fn const_context() {
    // The authority is computed at compile time
    // No runtime cost at all
    
    println!("Authority: {}", MY_AUTHORITY.as_str());
    
    // Can be used in static items too
    static STATIC_AUTHORITY: Authority = Authority::from_static("static.example.com");
    
    // Both MY_AUTHORITY and STATIC_AUTHORITY are fully validated
    // at compile time
}

from_static being const fn enables compile-time authority creation.

Comparison with Runtime Parsing

use http::uri::Authority;
 
fn runtime_vs_static() {
    // Runtime parsing - may fail, has overhead
    fn runtime_parsing() -> Result<Authority, http::uri::InvalidUri> {
        Authority::try_from("example.com".to_string())
    }
    
    // Static parsing - never fails for valid strings, zero overhead
    fn static_parsing() -> Authority {
        Authority::from_static("example.com")
        // No Result type - cannot fail if it compiles
    }
    
    // Runtime: handles dynamic input, returns Result
    let dynamic = std::env::var("HOST").unwrap_or_default();
    let authority: Authority = dynamic.parse().expect("invalid authority");
    
    // Static: handles known values, never fails at runtime
    const DEFAULT_AUTHORITY: Authority = Authority::from_static("localhost:8080");
    
    // Use static for compile-time known values
    // Use runtime parsing for dynamic values
}

Use from_static for known values; try_from for dynamic input.

Internal Mechanism

use http::uri::Authority;
 
fn internal_mechanism() {
    // from_static internally:
    // 1. Validates the string is valid UTF-8 (always true for string literals)
    // 2. Parses the authority components (host, port, userinfo)
    // 3. Validates each component per URI specification
    // 4. Returns Authority if valid, or panics in const context
    
    // The parsing in const context means:
    // - In debug mode: panics at runtime during initialization
    // - In release/optimized: evaluates at compile time
    // - In truly const context: compile-time error for invalid
    
    // For string literals (which are always &'static str):
    // - The compiler can evaluate from_static at compile time
    // - Invalid strings cause const evaluation error
}

Const evaluation happens during compilation for string literals.

Authority Components

use http::uri::Authority;
 
fn authority_components() {
    // Authority consists of: [userinfo@]host[:port]
    
    // Host only
    let host_only = Authority::from_static("example.com");
    assert_eq!(host_only.host(), "example.com");
    assert!(host_only.port().is_none());
    
    // Host with port
    let with_port = Authority::from_static("example.com:8080");
    assert_eq!(with_port.host(), "example.com");
    assert_eq!(with_port.port(), Some(8080));
    
    // IPv4 address
    let ipv4 = Authority::from_static("192.168.1.1:80");
    assert_eq!(ipv4.host(), "192.168.1.1");
    assert_eq!(ipv4.port(), Some(80));
    
    // IPv6 address (must be bracketed)
    let ipv6 = Authority::from_static("[::1]:8080");
    assert_eq!(ipv6.host(), "::1");  // Host is the IPv6 address without brackets
    assert_eq!(ipv6.port(), Some(8080));
    
    // Note: userinfo is not commonly used with from_static
    // as it's often dynamic or security-sensitive
}

from_static validates all authority components according to URI specifications.

Host Validation

use http::uri::Authority;
 
fn host_validation() {
    // Valid hosts:
    // - Domain names: letters, digits, hyphens, dots
    // - IPv4 addresses: four octets 0-255
    // - IPv6 addresses: bracketed hex notation
    
    // Valid examples:
    let _a = Authority::from_static("example.com");
    let _b = Authority::from_static("sub.example.com");
    let _c = Authority::from_static("my-service.local");
    let _d = Authority::from_static("192.168.0.1");
    let _e = Authority::from_static("[2001:db8::1]");
    
    // Invalid hosts would fail:
    // Authority::from_static("exa mple.com");   // Space in host
    // Authority::from_static("example..com");   // Empty label
    // Authority::from_static("999.999.999.999"); // Invalid IPv4
    
    // Each component is validated per RFC 3986
}

Host validation follows RFC 3986 URI specifications.

Port Validation

use http::uri::Authority;
 
fn port_validation() {
    // Port must be 0-65535
    
    // Valid ports:
    let _a = Authority::from_static("example.com:0");
    let _b = Authority::from_static("example.com:80");
    let _c = Authority::from_static("example.com:443");
    let _d = Authority::from_static("example.com:8080");
    let _e = Authority::from_static("example.com:65535");
    
    // Invalid ports would fail:
    // Authority::from_static("example.com:65536"); // Too large
    // Authority::from_static("example.com:-1");   // Negative
    // Authority::from_static("example.com:abc");  // Non-numeric
    
    // Access port at runtime:
    let auth = Authority::from_static("example.com:443");
    assert_eq!(auth.port(), Some(443));
    
    let no_port = Authority::from_static("example.com");
    assert!(no_port.port().is_none());
}

Ports are validated to be in the valid TCP/UDP port range.

Performance Benefits

use http::uri::Authority;
 
fn performance() {
    // from_static has zero runtime parsing cost
    // All validation happens at compile time
    
    // Compare with runtime parsing:
    // Authority::try_from(string) // Parses at runtime
    // string.parse::<Authority>() // Parses at runtime
    
    // With from_static:
    // - No heap allocation (uses static string)
    // - No parsing overhead
    // - No error handling needed (can't fail)
    // - Result is stored directly in binary
    
    // This is useful for:
    // - Default hosts/authorities
    // - Known service endpoints
    // - Configuration constants
    
    // Example: pre-validated service endpoints
    const API_AUTHORITY: Authority = Authority::from_static("api.example.com:443");
    const AUTH_AUTHORITY: Authority = Authority::from_static("auth.example.com:443");
    const CDN_AUTHORITY: Authority = Authority::from_static("cdn.example.com");
}

from_static eliminates runtime parsing for known authority strings.

Integration with URI Building

use http::uri::{Authority, Uri, Parts, Scheme};
 
fn uri_building() {
    // Authority::from_static integrates with URI building
    
    // Method 1: Direct URI creation
    let uri = Uri::from_static("https://example.com:443/path");
    // The authority "example.com:443" is parsed at compile time
    
    // Method 2: Builder pattern with Authority
    let authority = Authority::from_static("api.example.com:8080");
    let uri = Uri::builder()
        .scheme(Scheme::HTTPS)
        .authority(authority)
        .path_and_query("/api/v1")
        .build()
        .unwrap();
    
    // Method 3: Using const Authority in builder
    const MY_AUTHORITY: Authority = Authority::from_static("service.local:3000");
    let uri = Uri::builder()
        .authority(MY_AUTHORITY)
        .path_and_query("/health")
        .build()
        .unwrap();
    
    assert_eq!(uri.authority().unwrap().as_str(), "service.local:3000");
}

Authority::from_static works seamlessly with URI construction.

Working with Static Lifetime

use http::uri::Authority;
 
fn static_lifetime() {
    // from_static requires &'static str
    // Not just any &str, but specifically a static string
    
    // Works: string literals are &'static str
    let auth = Authority::from_static("example.com");
    
    // Would NOT work: dynamic strings don't live forever
    // fn dynamic_authority(s: String) -> Authority {
    //     Authority::from_static(&s)  // Error: not &'static str
    // }
    
    // For dynamic strings, use try_from:
    fn dynamic_authority(s: String) -> Result<Authority, http::uri::InvalidUri> {
        s.parse()
    }
    
    // The static requirement ensures the Authority can
    // safely reference the string without copying
    // (Internally, Authority may or may not copy depending on implementation)
}

from_static requires &'static str, not runtime-allocated strings.

Const Assertions

use http::uri::Authority;
 
fn const_assertions() {
    // Use from_static in const assertions for compile-time validation
    
    // Create compile-time validated constants
    const PROD_API: Authority = Authority::from_static("api.production.com:443");
    const DEV_API: Authority = Authority::from_static("api.development.com:8080");
    
    // Use in match expressions with compile-time known values
    fn get_authority(env: &str) -> Authority {
        match env {
            "production" => PROD_API,
            "development" => DEV_API,
            _ => Authority::from_static("localhost:8080"),
        }
    }
    
    // Each Authority constant is fully validated at compile time
    // Invalid authorities would cause compilation to fail
}

Constants with from_static ensure validity throughout the program.

Error Handling Differences

use http::uri::Authority;
 
fn error_handling() {
    // from_static: no error handling needed
    // If it compiles, it's valid
    let auth = Authority::from_static("example.com:80");
    // auth is guaranteed to be valid
    // No Result to unwrap, no panic possible
    
    // try_from / parse: requires error handling
    let result: Result<Authority, _> = "example.com:80".parse();
    match result {
        Ok(auth) => {
            // auth is valid
        }
        Err(e) => {
            // Handle invalid authority
            eprintln!("Invalid authority: {}", e);
        }
    }
    
    // Use from_static when:
    // - The authority is known at compile time
    // - You want zero runtime overhead
    // - You want compile-time validation
    
    // Use try_from/parse when:
    // - The authority comes from user input
    // - The authority comes from configuration files
    // - The authority is dynamically constructed
}

from_static removes error handling for known-good authorities.

Common Patterns

use http::uri::Authority;
use http::Uri;
 
fn common_patterns() {
    // Pattern 1: Service endpoints as constants
    const SERVICE_HOST: Authority = Authority::from_static("my-service.internal:8080");
    
    fn call_service() -> Result<(), Box<dyn std::error::Error>> {
        let uri = Uri::builder()
            .scheme("http")
            .authority(SERVICE_HOST)
            .path_and_query("/api/data")
            .build()?;
        
        // uri is constructed from pre-validated authority
        Ok(())
    }
    
    // Pattern 2: Default values for configuration
    const DEFAULT_HOST: Authority = Authority::from_static("localhost:8080");
    
    fn get_host() -> Authority {
        std::env::var("HOST")
            .ok()
            .and_then(|h| h.parse().ok())
            .unwrap_or(DEFAULT_HOST)
    }
    
    // Pattern 3: Multiple related endpoints
    const API_BASE: Authority = Authority::from_static("api.example.com");
    const AUTH_BASE: Authority = Authority::from_static("auth.example.com");
    const CDN_BASE: Authority = Authority::from_static("cdn.example.com");
    
    // All validated at compile time
    // No runtime parsing needed
}

Constants for known endpoints eliminate runtime overhead.

Synthesis

Quick reference:

Method Input Returns Validation
from_static &'static str Authority Compile-time
try_from &str or String Result<Authority, InvalidUri> Runtime
parse &str Result<Authority, InvalidUri> Runtime

When to use each:

use http::uri::Authority;
 
fn when_to_use() {
    // from_static: Compile-time known, static lifetime
    const PROD: Authority = Authority::from_static("api.prod.com:443");
    let local: Authority = Authority::from_static("localhost:8080");
    
    // try_from/parse: Dynamic input, unknown at compile time
    let from_config = "dynamic.example.com:80".parse::<Authority>();
    let from_user = Authority::try_from(user_provided_string);
}

Key insight: Authority::from_static leverages Rust's const evaluation to validate authority strings at compile time. As a const fn, it can execute during compilation when given a string literal, ensuring invalid authorities never make it past compilation. This provides three key benefits: (1) zero runtime parsing overhead since the validated Authority is embedded directly in the binary, (2) elimination of error handling code since the function returns Authority directly rather than Result, and (3) compile-time safety where invalid authorities cause compilation errors rather than runtime panics. The &'static str requirement ensures the input string lives for the program's entire duration, allowing the Authority to reference the static data without copying. For dynamic input from configuration files, user input, or environment variables, use try_from or parse which perform runtime validation and return Result<Authority, InvalidUri>. The pattern is particularly valuable for service endpoints, default hosts, and configuration constants that are known during development—using from_static makes these values impossible to get wrong in production.