oxirs-ttl 0.4.1

Turtle-family RDF parser and serializer for OxiRS - ported from Oxigraph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! IRI Normalization per RFC 3987 Section 5.3
//!
//! This module provides IRI normalization to convert IRIs into a canonical form
//! for efficient comparison and storage. Normalization includes:
//!
//! - Case normalization (scheme and host to lowercase)
//! - Percent-encoding normalization (decode unreserved characters)
//! - Path normalization (remove unnecessary dot-segments)
//! - Default port removal (http:80, https:443, etc.)
//! - Empty path to "/" for hierarchical URIs
//!
//! # RFC 3987 Compliance
//!
//! Implements the normalization algorithm from RFC 3987 Section 5.3 with
//! additional enhancements from RFC 3986.
//!
//! # Example
//!
//! ```
//! use oxirs_ttl::toolkit::iri_normalizer::{normalize_iri, NormalizedIri};
//!
//! // Case normalization
//! let iri = normalize_iri("HTTP://EXAMPLE.ORG/Path").expect("should succeed");
//! assert_eq!(iri.as_str(), "http://example.org/Path");
//!
//! // Percent-encoding normalization
//! let iri = normalize_iri("http://example.org/%7Euser").expect("should succeed");
//! assert_eq!(iri.as_str(), "http://example.org/~user");
//!
//! // Default port removal
//! let iri = normalize_iri("http://example.org:80/path").expect("should succeed");
//! assert_eq!(iri.as_str(), "http://example.org/path");
//!
//! // Path normalization
//! let iri = normalize_iri("http://example.org/a/./b/../c").expect("should succeed");
//! assert_eq!(iri.as_str(), "http://example.org/a/c");
//! ```

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;

/// A normalized IRI in canonical form
///
/// This type represents an IRI that has been normalized according to RFC 3987.
/// Normalized IRIs can be efficiently compared for equivalence.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NormalizedIri {
    /// The normalized IRI string
    iri: String,
}

impl NormalizedIri {
    /// Create a normalized IRI from a string
    ///
    /// This constructor assumes the IRI is already normalized.
    /// Use `normalize_iri()` to normalize an arbitrary IRI.
    pub fn new_unchecked(iri: String) -> Self {
        Self { iri }
    }

    /// Get the normalized IRI as a string slice
    pub fn as_str(&self) -> &str {
        &self.iri
    }

    /// Convert to owned String
    pub fn into_string(self) -> String {
        self.iri
    }

    /// Check if two IRIs are equivalent (same as PartialEq but explicit)
    pub fn is_equivalent(&self, other: &Self) -> bool {
        self.iri == other.iri
    }
}

impl fmt::Display for NormalizedIri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.iri)
    }
}

impl AsRef<str> for NormalizedIri {
    fn as_ref(&self) -> &str {
        &self.iri
    }
}

/// Error types for IRI normalization
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizationError {
    /// Invalid IRI format
    InvalidFormat(String),
    /// Invalid percent encoding
    InvalidPercentEncoding(String),
    /// Missing scheme
    MissingScheme,
    /// Invalid scheme
    InvalidScheme(String),
}

impl fmt::Display for NormalizationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFormat(msg) => write!(f, "Invalid IRI format: {}", msg),
            Self::InvalidPercentEncoding(seq) => {
                write!(f, "Invalid percent encoding: {}", seq)
            }
            Self::MissingScheme => write!(f, "IRI must have a scheme"),
            Self::InvalidScheme(s) => write!(f, "Invalid scheme: {}", s),
        }
    }
}

impl std::error::Error for NormalizationError {}

/// Result type for normalization operations
pub type NormalizationResult<T> = Result<T, NormalizationError>;

/// Normalize an IRI to canonical form
///
/// This function applies all normalization steps defined in RFC 3987:
/// - Case normalization (scheme and host to lowercase)
/// - Percent-encoding normalization
/// - Path normalization
/// - Default port removal
///
/// # Example
///
/// ```
/// use oxirs_ttl::toolkit::iri_normalizer::normalize_iri;
///
/// let iri = normalize_iri("HTTP://EXAMPLE.ORG:80/A/./B/../C").expect("should succeed");
/// assert_eq!(iri.as_str(), "http://example.org/A/C");
/// ```
pub fn normalize_iri(iri: &str) -> NormalizationResult<NormalizedIri> {
    if iri.is_empty() {
        return Err(NormalizationError::InvalidFormat(
            "IRI cannot be empty".to_string(),
        ));
    }

    // Parse components
    let components = parse_iri_components(iri)?;

    // Apply normalization
    let normalized = normalize_components(&components)?;

    Ok(NormalizedIri::new_unchecked(normalized))
}

/// IRI components for normalization
#[derive(Debug, Clone)]
struct IriComponents {
    scheme: String,
    authority: Option<Authority>,
    path: String,
    query: Option<String>,
    fragment: Option<String>,
}

/// Authority component (userinfo@host:port)
#[derive(Debug, Clone)]
struct Authority {
    userinfo: Option<String>,
    host: String,
    port: Option<u16>,
}

/// Parse IRI into components
fn parse_iri_components(iri: &str) -> NormalizationResult<IriComponents> {
    // Extract scheme
    let colon_pos = iri.find(':').ok_or(NormalizationError::MissingScheme)?;
    let scheme = iri[..colon_pos].to_string();

    if scheme.is_empty() || !is_valid_scheme(&scheme) {
        return Err(NormalizationError::InvalidScheme(scheme));
    }

    let rest = &iri[colon_pos + 1..];

    // Check for authority (starts with //)
    let (authority, path_query_fragment) = if let Some(after_slashes) = rest.strip_prefix("//") {
        let auth_end = after_slashes
            .find(['/', '?', '#'])
            .unwrap_or(after_slashes.len());
        let authority_str = &after_slashes[..auth_end];
        let authority = parse_authority(authority_str)?;
        (Some(authority), &after_slashes[auth_end..])
    } else {
        (None, rest)
    };

    // Parse path, query, and fragment
    let (path, query_fragment) = if let Some(q_pos) = path_query_fragment.find('?') {
        (
            path_query_fragment[..q_pos].to_string(),
            &path_query_fragment[q_pos + 1..],
        )
    } else if let Some(f_pos) = path_query_fragment.find('#') {
        (
            path_query_fragment[..f_pos].to_string(),
            &path_query_fragment[f_pos..],
        )
    } else {
        (path_query_fragment.to_string(), "")
    };

    let (query, fragment) = if !query_fragment.is_empty() {
        if let Some(f_pos) = query_fragment.find('#') {
            (
                Some(query_fragment[..f_pos].to_string()),
                Some(query_fragment[f_pos + 1..].to_string()),
            )
        } else {
            (Some(query_fragment.to_string()), None)
        }
    } else {
        (None, None)
    };

    Ok(IriComponents {
        scheme,
        authority,
        path,
        query,
        fragment,
    })
}

/// Parse authority component
fn parse_authority(authority: &str) -> NormalizationResult<Authority> {
    if authority.is_empty() {
        return Ok(Authority {
            userinfo: None,
            host: String::new(),
            port: None,
        });
    }

    // Split userinfo@host:port
    let (userinfo, host_port) = if let Some(at_pos) = authority.rfind('@') {
        (
            Some(authority[..at_pos].to_string()),
            &authority[at_pos + 1..],
        )
    } else {
        (None, authority)
    };

    // Parse host and port
    let (host, port) = parse_host_port(host_port)?;

    Ok(Authority {
        userinfo,
        host,
        port,
    })
}

/// Parse host:port
fn parse_host_port(host_port: &str) -> NormalizationResult<(String, Option<u16>)> {
    // IPv6 address
    if let Some(bracket_start) = host_port.find('[') {
        let bracket_end = host_port.find(']').ok_or_else(|| {
            NormalizationError::InvalidFormat("Unclosed IPv6 bracket".to_string())
        })?;
        let host = host_port[bracket_start..=bracket_end].to_string();
        let rest = &host_port[bracket_end + 1..];
        let port = if let Some(port_str) = rest.strip_prefix(':') {
            Some(port_str.parse::<u16>().map_err(|_| {
                NormalizationError::InvalidFormat(format!("Invalid port: {}", port_str))
            })?)
        } else if rest.is_empty() {
            None
        } else {
            return Err(NormalizationError::InvalidFormat(
                "Invalid characters after IPv6 address".to_string(),
            ));
        };
        return Ok((host, port));
    }

    // Regular host:port
    if let Some(colon_pos) = host_port.rfind(':') {
        let potential_port = &host_port[colon_pos + 1..];
        // Only treat as port if it's all digits
        if potential_port.chars().all(|c| c.is_ascii_digit()) {
            let port = potential_port.parse::<u16>().map_err(|_| {
                NormalizationError::InvalidFormat(format!("Invalid port: {}", potential_port))
            })?;
            Ok((host_port[..colon_pos].to_string(), Some(port)))
        } else {
            Ok((host_port.to_string(), None))
        }
    } else {
        Ok((host_port.to_string(), None))
    }
}

/// Normalize IRI components
fn normalize_components(components: &IriComponents) -> NormalizationResult<String> {
    // 1. Case normalization: scheme to lowercase
    let scheme = components.scheme.to_lowercase();

    // 2. Authority normalization
    let authority_str = if let Some(ref auth) = components.authority {
        let mut parts = Vec::new();

        // Userinfo (if present)
        if let Some(ref userinfo) = auth.userinfo {
            let normalized_userinfo = normalize_percent_encoding(userinfo)?;
            parts.push(format!("{}@", normalized_userinfo));
        }

        // Host: lowercase for reg-name (not IPv6)
        let normalized_host = if auth.host.starts_with('[') {
            // IPv6: keep as-is (case-insensitive hex is normalized to lowercase)
            auth.host.to_lowercase()
        } else {
            // Reg-name: lowercase + percent-encoding normalization
            normalize_percent_encoding(&auth.host.to_lowercase())?
        };
        parts.push(normalized_host);

        // Port: remove default ports
        if let Some(port) = auth.port {
            if !is_default_port(&scheme, port) {
                parts.push(format!(":{}", port));
            }
        }

        format!("//{}", parts.concat())
    } else {
        String::new()
    };

    // 3. Path normalization
    let normalized_path = normalize_path(&components.path, components.authority.is_some())?;

    // 4. Query normalization
    let query_str = if let Some(ref query) = components.query {
        format!("?{}", normalize_percent_encoding(query)?)
    } else {
        String::new()
    };

    // 5. Fragment normalization
    let fragment_str = if let Some(ref fragment) = components.fragment {
        format!("#{}", normalize_percent_encoding(fragment)?)
    } else {
        String::new()
    };

    // Reconstruct normalized IRI
    Ok(format!(
        "{}:{}{}{}{}",
        scheme, authority_str, normalized_path, query_str, fragment_str
    ))
}

/// Normalize percent-encoding (decode unreserved characters)
///
/// RFC 3986: Unreserved characters are A-Z, a-z, 0-9, -, ., _, ~
/// These should not be percent-encoded.
fn normalize_percent_encoding(s: &str) -> NormalizationResult<String> {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '%' {
            // Read next two characters
            let hex1 = chars
                .next()
                .ok_or_else(|| NormalizationError::InvalidPercentEncoding(format!("%{}", s)))?;
            let hex2 = chars.next().ok_or_else(|| {
                NormalizationError::InvalidPercentEncoding(format!("%{}{}", hex1, s))
            })?;

            let hex_str = format!("{}{}", hex1, hex2);
            let byte = u8::from_str_radix(&hex_str, 16)
                .map_err(|_| NormalizationError::InvalidPercentEncoding(format!("%{}", hex_str)))?;

            // Check if it's an unreserved character
            let decoded = byte as char;
            if is_unreserved(decoded) {
                // Decode unreserved characters
                result.push(decoded);
            } else {
                // Keep percent-encoded (normalize to uppercase)
                result.push_str(&format!("%{}", hex_str.to_uppercase()));
            }
        } else {
            result.push(ch);
        }
    }

    Ok(result)
}

/// Check if a character is unreserved (RFC 3986)
fn is_unreserved(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || ch == '-' || ch == '.' || ch == '_' || ch == '~'
}

/// Normalize path component
fn normalize_path(path: &str, has_authority: bool) -> NormalizationResult<String> {
    // Empty path for hierarchical URIs should become "/"
    if path.is_empty() && has_authority {
        return Ok("/".to_string());
    }

    // Remove dot segments
    let normalized = remove_dot_segments(path);

    // Percent-encoding normalization
    normalize_percent_encoding(&normalized)
}

/// Remove dot segments from path (RFC 3986 Section 5.2.4)
fn remove_dot_segments(path: &str) -> String {
    let mut output = Vec::new();
    let segments: Vec<&str> = path.split('/').collect();
    let has_trailing_slash = path.ends_with('/') && path.len() > 1;

    for (i, segment) in segments.iter().enumerate() {
        match *segment {
            "" => {
                // Skip empty segments except at the beginning
                if i == 0 {
                    // Keep leading slash
                }
            }
            "." => {
                // Skip current directory
            }
            ".." => {
                // Go up one level (pop last segment)
                output.pop();
            }
            _ => {
                // Regular segment
                output.push(*segment);
            }
        }
    }

    // Reconstruct path
    if path.starts_with('/') {
        if output.is_empty() {
            "/".to_string()
        } else {
            let base_path = format!("/{}", output.join("/"));
            if has_trailing_slash {
                format!("{}/", base_path)
            } else {
                base_path
            }
        }
    } else if output.is_empty() {
        String::new()
    } else {
        let base_path = output.join("/");
        if has_trailing_slash {
            format!("{}/", base_path)
        } else {
            base_path
        }
    }
}

/// Check if port is the default for the scheme
fn is_default_port(scheme: &str, port: u16) -> bool {
    get_default_port(scheme) == Some(port)
}

/// Get default port for a scheme
fn get_default_port(scheme: &str) -> Option<u16> {
    DEFAULT_PORTS.get(scheme).copied()
}

// Default ports for common schemes
static DEFAULT_PORTS: once_cell::sync::Lazy<HashMap<&'static str, u16>> =
    once_cell::sync::Lazy::new(|| {
        let mut m = HashMap::new();
        m.insert("http", 80);
        m.insert("https", 443);
        m.insert("ftp", 21);
        m.insert("ftps", 990);
        m.insert("ssh", 22);
        m.insert("telnet", 23);
        m.insert("smtp", 25);
        m.insert("pop3", 110);
        m.insert("imap", 143);
        m.insert("ldap", 389);
        m.insert("ldaps", 636);
        m.insert("ws", 80);
        m.insert("wss", 443);
        m
    });

/// Check if a string is a valid scheme
fn is_valid_scheme(scheme: &str) -> bool {
    if scheme.is_empty() {
        return false;
    }
    let mut chars = scheme.chars();

    // First character must be ASCII letter
    let first = chars.next().expect("iterator should have next element");
    if !first.is_ascii_alphabetic() {
        return false;
    }

    // Rest can be ASCII letter, digit, +, -, .
    chars.all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
}

/// Generic components of an IRI reference (RFC 3986 §3), where every component but
/// `path` may be absent for a relative reference.
struct ReferenceComponents {
    scheme: Option<String>,
    authority: Option<String>,
    path: String,
    query: Option<String>,
    fragment: Option<String>,
}

/// Split an IRI reference into its generic components without requiring a scheme,
/// unlike [`parse_iri_components`] which is only valid for absolute IRIs.
fn split_generic_reference(reference: &str) -> ReferenceComponents {
    let (before_fragment, fragment) = match reference.find('#') {
        Some(i) => (&reference[..i], Some(reference[i + 1..].to_string())),
        None => (reference, None),
    };

    let (before_query, query) = match before_fragment.find('?') {
        Some(i) => (
            &before_fragment[..i],
            Some(before_fragment[i + 1..].to_string()),
        ),
        None => (before_fragment, None),
    };

    // A scheme, if present, is always the component preceding the first ':' and must
    // consist solely of valid scheme characters (this also naturally rules out a ':'
    // appearing later in a path segment, matching the RFC 3986 §3.3 rule that a
    // relative-path reference's first segment cannot contain a colon).
    let scheme_end = before_query.find(':').filter(|&i| {
        let candidate = &before_query[..i];
        !candidate.is_empty()
            && candidate
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic())
            && candidate
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    });

    let (scheme, rest) = match scheme_end {
        Some(i) => (Some(before_query[..i].to_string()), &before_query[i + 1..]),
        None => (None, before_query),
    };

    let (authority, path) = if let Some(after_slashes) = rest.strip_prefix("//") {
        let end = after_slashes.find('/').unwrap_or(after_slashes.len());
        (
            Some(after_slashes[..end].to_string()),
            after_slashes[end..].to_string(),
        )
    } else {
        (None, rest.to_string())
    };

    ReferenceComponents {
        scheme,
        authority,
        path,
        query,
        fragment,
    }
}

/// Recompose generic reference components back into an IRI string (RFC 3986 §5.3).
fn recompose(components: &ReferenceComponents) -> String {
    let mut result = String::new();
    if let Some(scheme) = &components.scheme {
        result.push_str(scheme);
        result.push(':');
    }
    if let Some(authority) = &components.authority {
        result.push_str("//");
        result.push_str(authority);
    }
    result.push_str(&components.path);
    if let Some(query) = &components.query {
        result.push('?');
        result.push_str(query);
    }
    if let Some(fragment) = &components.fragment {
        result.push('#');
        result.push_str(fragment);
    }
    result
}

/// Merge a base path with a relative-path reference (RFC 3986 §5.3, "merge").
fn merge_paths(base_has_authority: bool, base_path: &str, ref_path: &str) -> String {
    if base_has_authority && base_path.is_empty() {
        format!("/{ref_path}")
    } else {
        match base_path.rfind('/') {
            Some(i) => format!("{}{}", &base_path[..=i], ref_path),
            None => ref_path.to_string(),
        }
    }
}

/// Remove `.` and `..` dot-segments from a path per the precise algorithm in
/// RFC 3986 §5.2.4.
///
/// This differs from the internal `remove_dot_segments` used by [`normalize_iri`] in
/// that it follows the RFC's step-by-step buffer algorithm exactly (including
/// preserving a trailing slash produced by a trailing `.`/`..` segment), which matters
/// for correct reference resolution.
fn remove_dot_segments_rfc3986(path: &str) -> String {
    fn remove_last_output_segment(output: &mut String) {
        match output.rfind('/') {
            Some(pos) => output.truncate(pos),
            None => output.clear(),
        }
    }

    let mut input = path;
    let mut output = String::new();

    while !input.is_empty() {
        if let Some(rest) = input.strip_prefix("../") {
            input = rest;
        } else if let Some(rest) = input.strip_prefix("./") {
            input = rest;
        } else if input.starts_with("/./") {
            // Replace the "/./ " prefix with "/", keeping the leading slash.
            input = &input[2..];
        } else if input == "/." {
            input = "/";
        } else if input.starts_with("/../") {
            // Replace the "/../ " prefix with "/" and drop the last output segment.
            input = &input[3..];
            remove_last_output_segment(&mut output);
        } else if input == "/.." {
            input = "/";
            remove_last_output_segment(&mut output);
        } else if input == "." || input == ".." {
            input = "";
        } else {
            // Move the first path segment (including a leading '/' if present) to
            // the output buffer.
            let start = usize::from(input.starts_with('/'));
            let end = input[start..]
                .find('/')
                .map(|i| i + start)
                .unwrap_or(input.len());
            output.push_str(&input[..end]);
            input = &input[end..];
        }
    }

    output
}

/// Resolve a (possibly relative) IRI reference against a base IRI, following the
/// reference resolution algorithm defined in RFC 3986 §5.2 / §5.3 (also applicable to
/// IRIs per RFC 3987). Handles absolute references, network-path references
/// (`//host/path`), absolute-path references (`/path`), relative-path references, and
/// same-document references (differing only in query/fragment), including dot-segment
/// removal.
///
/// # Example
///
/// ```
/// use oxirs_ttl::toolkit::iri_normalizer::resolve_reference;
///
/// assert_eq!(
///     resolve_reference("http://example.org/data", "foo"),
///     "http://example.org/foo"
/// );
/// assert_eq!(
///     resolve_reference("http://example.org/a/b/c", "/x/y"),
///     "http://example.org/x/y"
/// );
/// assert_eq!(
///     resolve_reference("http://example.org/a/b/c", "../d"),
///     "http://example.org/a/d"
/// );
/// assert_eq!(
///     resolve_reference("http://example.org/a/b#frag1", "#frag2"),
///     "http://example.org/a/b#frag2"
/// );
/// ```
pub fn resolve_reference(base: &str, reference: &str) -> String {
    let ref_components = split_generic_reference(reference);

    if ref_components.scheme.is_some() {
        return recompose(&ReferenceComponents {
            scheme: ref_components.scheme,
            authority: ref_components.authority,
            path: remove_dot_segments_rfc3986(&ref_components.path),
            query: ref_components.query,
            fragment: ref_components.fragment,
        });
    }

    let base_components = split_generic_reference(base);

    let (t_authority, t_path, t_query) = if ref_components.authority.is_some() {
        (
            ref_components.authority,
            remove_dot_segments_rfc3986(&ref_components.path),
            ref_components.query,
        )
    } else if ref_components.path.is_empty() {
        (
            base_components.authority,
            base_components.path,
            ref_components.query.or(base_components.query),
        )
    } else if ref_components.path.starts_with('/') {
        (
            base_components.authority,
            remove_dot_segments_rfc3986(&ref_components.path),
            ref_components.query,
        )
    } else {
        let merged = merge_paths(
            base_components.authority.is_some(),
            &base_components.path,
            &ref_components.path,
        );
        (
            base_components.authority,
            remove_dot_segments_rfc3986(&merged),
            ref_components.query,
        )
    };

    recompose(&ReferenceComponents {
        scheme: base_components.scheme,
        authority: t_authority,
        path: t_path,
        query: t_query,
        fragment: ref_components.fragment,
    })
}

/// Compare two IRIs for equivalence
///
/// This function normalizes both IRIs and compares them.
/// Use this for IRI comparison instead of string equality.
///
/// # Example
///
/// ```
/// use oxirs_ttl::toolkit::iri_normalizer::iris_equivalent;
///
/// assert!(iris_equivalent(
///     "HTTP://EXAMPLE.ORG/path",
///     "http://example.org/path"
/// ).expect("should succeed"));
///
/// assert!(iris_equivalent(
///     "http://example.org:80/path",
///     "http://example.org/path"
/// ).expect("should succeed"));
///
/// assert!(!iris_equivalent(
///     "http://example.org/path1",
///     "http://example.org/path2"
/// ).expect("should succeed"));
/// ```
pub fn iris_equivalent(iri1: &str, iri2: &str) -> NormalizationResult<bool> {
    let normalized1 = normalize_iri(iri1)?;
    let normalized2 = normalize_iri(iri2)?;
    Ok(normalized1.is_equivalent(&normalized2))
}

/// Normalize an IRI and return as a Cow (avoids allocation if already normalized)
///
/// This is more efficient than `normalize_iri()` when the IRI is likely already normalized.
pub fn normalize_iri_cow(iri: &str) -> NormalizationResult<Cow<'_, str>> {
    let normalized = normalize_iri(iri)?;
    if normalized.as_str() == iri {
        Ok(Cow::Borrowed(iri))
    } else {
        Ok(Cow::Owned(normalized.into_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_case_normalization() {
        let iri = normalize_iri("HTTP://EXAMPLE.ORG/Path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/Path");
    }

    #[test]
    fn test_percent_encoding_normalization() {
        // Decode unreserved characters
        let iri = normalize_iri("http://example.org/%7Euser").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/~user");

        let iri = normalize_iri("http://example.org/%41%42%43").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/ABC");

        // Keep reserved characters encoded (but uppercase)
        let iri = normalize_iri("http://example.org/path%20with%20spaces").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/path%20with%20spaces");
    }

    #[test]
    fn test_default_port_removal() {
        let iri = normalize_iri("http://example.org:80/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/path");

        let iri = normalize_iri("https://example.org:443/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "https://example.org/path");

        // Non-default port should be kept
        let iri = normalize_iri("http://example.org:8080/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org:8080/path");
    }

    #[test]
    fn test_path_normalization() {
        let iri = normalize_iri("http://example.org/a/./b/../c").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/a/c");

        let iri = normalize_iri("http://example.org/./a/b").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/a/b");

        let iri = normalize_iri("http://example.org/a/b/..").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/a");
    }

    #[test]
    fn test_empty_path_normalization() {
        let iri = normalize_iri("http://example.org").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/");
    }

    #[test]
    fn test_query_and_fragment() {
        let iri = normalize_iri("http://example.org/path?query=value#fragment").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/path?query=value#fragment");

        // Percent-encoding in query and fragment
        let iri = normalize_iri("http://example.org/path?q=%41#%42").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://example.org/path?q=A#B");
    }

    #[test]
    fn test_ipv6_address() {
        let iri = normalize_iri("http://[2001:db8::1]/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://[2001:db8::1]/path");

        let iri = normalize_iri("http://[2001:DB8::1]:8080/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://[2001:db8::1]:8080/path");
    }

    #[test]
    fn test_userinfo() {
        let iri = normalize_iri("http://user:pass@example.org/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://user:pass@example.org/path");

        let iri = normalize_iri("http://%41%42%43@example.org/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "http://ABC@example.org/path");
    }

    #[test]
    fn test_iris_equivalent() {
        assert!(
            iris_equivalent("HTTP://EXAMPLE.ORG/path", "http://example.org/path")
                .expect("valid IRI")
        );

        assert!(
            iris_equivalent("http://example.org:80/path", "http://example.org/path")
                .expect("valid IRI")
        );

        assert!(
            iris_equivalent("http://example.org/a/./b/../c", "http://example.org/a/c")
                .expect("valid IRI")
        );

        assert!(
            !iris_equivalent("http://example.org/path1", "http://example.org/path2")
                .expect("valid IRI")
        );
    }

    #[test]
    fn test_complex_normalization() {
        let iri = normalize_iri("HTTP://USER@EXAMPLE.ORG:80/A/./B/../C/%7Euser?Q=%41#%42")
            .expect("valid IRI");
        assert_eq!(iri.as_str(), "http://USER@example.org/A/C/~user?Q=A#B");
    }

    #[test]
    fn test_non_http_schemes() {
        let iri = normalize_iri("ftp://example.org:21/path").expect("valid IRI");
        assert_eq!(iri.as_str(), "ftp://example.org/path");

        let iri = normalize_iri("urn:isbn:0451450523").expect("valid IRI");
        assert_eq!(iri.as_str(), "urn:isbn:0451450523");
    }

    #[test]
    fn test_invalid_iri() {
        assert!(normalize_iri("").is_err());
        assert!(normalize_iri("not an iri").is_err());
        assert!(normalize_iri("http://example.org/%ZZ").is_err());
    }

    #[test]
    fn test_normalized_iri_methods() {
        let iri1 = normalize_iri("http://example.org/path").expect("valid IRI");
        let iri2 = normalize_iri("HTTP://EXAMPLE.ORG/path").expect("valid IRI");

        assert_eq!(iri1.as_str(), "http://example.org/path");
        assert!(iri1.is_equivalent(&iri2));
        assert_eq!(iri1, iri2);

        let cloned = iri1.clone();
        assert_eq!(iri1, cloned);
    }

    #[test]
    fn test_normalize_iri_cow() {
        // Already normalized - should return Borrowed
        let iri = "http://example.org/path";
        let result = normalize_iri_cow(iri).expect("valid IRI");
        assert!(matches!(result, Cow::Borrowed(_)));
        assert_eq!(result, iri);

        // Not normalized - should return Owned
        let iri = "HTTP://EXAMPLE.ORG/path";
        let result = normalize_iri_cow(iri).expect("valid IRI");
        assert!(matches!(result, Cow::Owned(_)));
        assert_eq!(result, "http://example.org/path");
    }

    #[test]
    fn test_urn_normalization() {
        // URN scheme normalization
        let iri = normalize_iri("URN:ISBN:0451450523").expect("valid IRI");
        assert_eq!(iri.as_str(), "urn:ISBN:0451450523");
    }

    #[test]
    fn test_resolve_reference_relative_path_no_trailing_slash_in_base() {
        // Base without a trailing slash: the last path segment must be dropped, not
        // treated as a directory (regression for naive `format!("{base}{iri}")`).
        assert_eq!(
            resolve_reference("http://example.org/data", "foo"),
            "http://example.org/foo"
        );
    }

    #[test]
    fn test_resolve_reference_absolute_path() {
        assert_eq!(
            resolve_reference("http://example.org/a/b/c", "/x/y"),
            "http://example.org/x/y"
        );
    }

    #[test]
    fn test_resolve_reference_dot_segments() {
        assert_eq!(
            resolve_reference("http://example.org/a/b/c", "../d"),
            "http://example.org/a/d"
        );
        assert_eq!(
            resolve_reference("http://a/b/c/d;p?q", "./g"),
            "http://a/b/c/g"
        );
        assert_eq!(
            resolve_reference("http://a/b/c/d;p?q", "../../../g"),
            "http://a/g"
        );
    }

    #[test]
    fn test_resolve_reference_fragment_only() {
        assert_eq!(
            resolve_reference("http://example.org/a/b#frag1", "#frag2"),
            "http://example.org/a/b#frag2"
        );
    }

    #[test]
    fn test_resolve_reference_absolute_reference_unchanged() {
        assert_eq!(
            resolve_reference("http://example.org/a/", "http://other.org/z"),
            "http://other.org/z"
        );
    }

    #[test]
    fn test_resolve_reference_network_path() {
        assert_eq!(
            resolve_reference("http://example.org/a/b", "//other.org/z"),
            "http://other.org/z"
        );
    }

    #[test]
    fn test_resolve_reference_query_only() {
        assert_eq!(
            resolve_reference("http://example.org/a/b?x=1", "?y=2"),
            "http://example.org/a/b?y=2"
        );
    }

    #[test]
    fn test_resolve_reference_empty_reference_same_document() {
        assert_eq!(
            resolve_reference("http://example.org/a/b?x=1#f", ""),
            "http://example.org/a/b?x=1"
        );
    }

    #[test]
    fn test_trailing_slash() {
        let iri1 = normalize_iri("http://example.org/path/").expect("valid IRI");
        let iri2 = normalize_iri("http://example.org/path").expect("valid IRI");

        // These should NOT be equivalent (trailing slash matters)
        assert_ne!(iri1, iri2);
        assert_eq!(iri1.as_str(), "http://example.org/path/");
        assert_eq!(iri2.as_str(), "http://example.org/path");
    }
}