rez-next-version 0.3.0

Ultra-fast version parsing and comparison with 117x performance improvement - core component of Rez-Next
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
//! Version range implementation - full rez-compatible version range parsing

use super::Version;
use rez_next_common::RezCoreError;
use serde::{Deserialize, Serialize};

/// A single bound in a version range
#[derive(Clone, Debug, PartialEq, Eq)]
enum Bound {
    /// >= version
    Ge(Version),
    /// > version
    Gt(Version),
    /// <= version
    Le(Version),
    /// < version
    Lt(Version),
    /// == version (exact match)
    Eq(Version),
    /// != version
    Ne(Version),
    /// ~= version (compatible release: >= version AND < next major.minor)
    Compatible(Version),
    /// Any version (no constraint)
    Any,
    /// Empty set (no versions match)
    None,
}

/// A conjunction of bounds (all must be satisfied)
#[derive(Clone, Debug, PartialEq, Eq)]
struct BoundSet {
    bounds: Vec<Bound>,
}

impl BoundSet {
    fn any() -> Self {
        BoundSet {
            bounds: vec![Bound::Any],
        }
    }

    fn none() -> Self {
        BoundSet {
            bounds: vec![Bound::None],
        }
    }

    fn contains(&self, version: &Version) -> bool {
        for bound in &self.bounds {
            if !bound_matches(bound, version) {
                return false;
            }
        }
        true
    }
}

fn bound_matches(bound: &Bound, version: &Version) -> bool {
    match bound {
        Bound::Any => true,
        Bound::None => false,
        Bound::Ge(v) => version >= v,
        Bound::Gt(v) => version > v,
        Bound::Le(v) => version <= v,
        Bound::Lt(v) => version < v,
        Bound::Eq(v) => version == v,
        Bound::Ne(v) => version != v,
        Bound::Compatible(v) => {
            // ~= M.N means >= M.N AND < M.(N+1), or ~= M.N.P means >= M.N.P AND < M.N+1
            // For rez we implement as: >= v AND same prefix up to second-to-last component
            if version < v {
                return false;
            }
            // Compatible release: upper bound is next minor/patch
            let parts = v.as_str().split('.').collect::<Vec<_>>();
            if parts.len() < 2 {
                return true;
            }
            let prefix = &parts[..parts.len() - 1].join(".");
            // version must start with same prefix
            version.as_str().starts_with(&format!("{}.", prefix))
                || version.as_str() == prefix.as_str()
        }
    }
}

/// Version range representation - a disjunction of BoundSets (union of intersections)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionRange {
    /// Cached string representation
    pub range_str: String,
    /// Parsed bound sets (disjunction - any must match)
    #[serde(skip)]
    bound_sets: Vec<BoundSet>,
    /// Whether the range was successfully parsed
    #[serde(skip)]
    is_parsed: bool,
    /// Ranges to subtract (for set difference operations)
    #[serde(skip)]
    subtract_from: Vec<VersionRange>,
}

impl VersionRange {
    /// Create a new version range from a string
    pub fn new(range_str: String) -> Result<Self, RezCoreError> {
        Self::parse(&range_str)
    }

    /// Create a version range that matches any version (equivalent to `""` or `"*"`)
    pub fn any() -> Self {
        VersionRange {
            range_str: String::new(),
            bound_sets: vec![BoundSet::any()],
            is_parsed: true,
            subtract_from: Vec::new(),
        }
    }

    /// Create a version range that matches no version (empty set)
    pub fn none() -> Self {
        VersionRange {
            range_str: "!*".to_string(),
            bound_sets: vec![BoundSet::none()],
            is_parsed: true,
            subtract_from: Vec::new(),
        }
    }

    /// Parse a version range string
    ///
    /// Supported formats:
    /// - `""` or `"*"` - any version
    /// - `">=1.0"` - single constraint
    /// - `">=1.0,<2.0"` - comma-separated AND constraints (rez style)
    /// - `">=1.0 <2.0"` - space-separated AND constraints
    /// - `"1.0+"` - rez shorthand for `>=1.0`
    /// - `"<1.0|>=2.0"` - pipe-separated OR constraints
    /// - `"==1.0"` - exact version
    /// - `"~=1.4"` - compatible release
    pub fn parse(range_str: &str) -> Result<Self, RezCoreError> {
        let trimmed = range_str.trim();
        let bound_sets = parse_range_str(trimmed)?;
        Ok(VersionRange {
            range_str: range_str.to_string(),
            bound_sets,
            is_parsed: true,
            subtract_from: Vec::new(),
        })
    }

    /// Check if a version satisfies this range
    pub fn contains(&self, version: &Version) -> bool {
        if !self.is_parsed || self.bound_sets.is_empty() {
            return true;
        }
        // Disjunction: any bound_set matching means the version is included
        let in_self = self.bound_sets.iter().any(|bs| bs.contains(version));
        if !in_self {
            return false;
        }
        // Subtract: if version is in any subtract range, exclude it
        for sub_range in &self.subtract_from {
            if sub_range.contains(version) {
                return false;
            }
        }
        true
    }

    /// Get the string representation
    pub fn as_str(&self) -> &str {
        &self.range_str
    }

    /// Check if this range intersects with another range
    pub fn intersects(&self, other: &VersionRange) -> bool {
        // Conservative: if either is "any", they intersect
        if self.is_any() || other.is_any() {
            return true;
        }
        // Check if the ranges have any overlap by checking bounds interaction
        // For exact versions, check containment
        for bs_self in &self.bound_sets {
            for bs_other in &other.bound_sets {
                // Check if these two bound sets can co-exist
                if bound_sets_intersect(bs_self, bs_other) {
                    return true;
                }
            }
        }
        false
    }

    /// Compute the intersection of two ranges
    pub fn intersect(&self, other: &VersionRange) -> Option<VersionRange> {
        if self.is_any() {
            return Some(other.clone());
        }
        if other.is_any() {
            return Some(self.clone());
        }
        // Merge all bound sets with AND semantics
        // Only include merged sets that are satisfiable (not trivially empty)
        let mut result_sets = Vec::new();
        for bs_self in &self.bound_sets {
            for bs_other in &other.bound_sets {
                let mut merged = bs_self.bounds.clone();
                merged.extend(bs_other.bounds.clone());
                let merged_set = BoundSet { bounds: merged };
                // Only include if this merged set is satisfiable
                if is_bound_set_satisfiable(&merged_set) {
                    result_sets.push(merged_set);
                }
            }
        }

        if result_sets.is_empty() {
            return None;
        }
        let new_str = format!("({})&({})", self.range_str, other.range_str);
        let mut combined_subtracts = self.subtract_from.clone();
        combined_subtracts.extend(other.subtract_from.clone());
        Some(VersionRange {
            range_str: new_str,
            bound_sets: result_sets,
            is_parsed: true,
            subtract_from: combined_subtracts,
        })
    }

    /// Compute the union of two ranges (pipe-separated)
    pub fn union(&self, other: &VersionRange) -> VersionRange {
        let new_str = format!("{}|{}", self.range_str, other.range_str);
        let mut sets = self.bound_sets.clone();
        sets.extend(other.bound_sets.clone());
        VersionRange {
            range_str: new_str,
            bound_sets: sets,
            is_parsed: true,
            subtract_from: Vec::new(),
        }
    }

    /// Compute the difference of two ranges: versions in self but not in other
    /// Returns None if the result would be empty
    pub fn subtract(&self, other: &VersionRange) -> Option<VersionRange> {
        if other.is_any() {
            return None; // self - any = empty
        }
        if other.is_empty() {
            return Some(self.clone());
        }
        if self.is_empty() {
            return None;
        }
        // Use subtract_from field: self with other excluded via contains() check
        let new_str = format!("({})-({})", self.range_str, other.range_str);
        let mut subtracts = self.subtract_from.clone();
        subtracts.push(other.clone());
        let range = VersionRange {
            range_str: new_str,
            bound_sets: self.bound_sets.clone(),
            is_parsed: true,
            subtract_from: subtracts,
        };
        // Quick sanity: at least one probe version must be in the result
        let probes = self.collect_probe_versions_with_other(other);
        let has_any = probes.iter().any(|v| range.contains(v));
        if has_any {
            Some(range)
        } else {
            None
        }
    }

    /// Check if this range is the "any" range (matches all versions)
    pub fn is_any(&self) -> bool {
        let s = self.range_str.trim();
        if s.is_empty() || s == "*" {
            return true;
        }
        // Check if all bound sets are Any
        self.bound_sets
            .iter()
            .all(|bs| bs.bounds.is_empty() || bs.bounds.iter().all(|b| matches!(b, Bound::Any)))
    }

    /// Check if this range is a subset of another range
    /// (every version in self is also in other)
    pub fn is_subset_of(&self, other: &VersionRange) -> bool {
        if other.is_any() {
            return true;
        }
        if self.is_any() {
            return other.is_any();
        }
        if self.is_empty() {
            return true;
        }
        let probe_versions = self.collect_probe_versions_with_other(other);
        for v in &probe_versions {
            if self.contains(v) && !other.contains(v) {
                return false;
            }
        }
        true
    }

    /// Check if this range is a superset of another range
    pub fn is_superset_of(&self, other: &VersionRange) -> bool {
        other.is_subset_of(self)
    }

    /// Collect probe versions from both self and other's bounds, plus "beyond" versions
    fn collect_probe_versions_with_other(&self, other: &VersionRange) -> Vec<Version> {
        let mut versions = Vec::new();
        for range in [self as &VersionRange, other] {
            for bs in &range.bound_sets {
                for bound in &bs.bounds {
                    match bound {
                        Bound::Ge(v)
                        | Bound::Gt(v)
                        | Bound::Le(v)
                        | Bound::Lt(v)
                        | Bound::Eq(v)
                        | Bound::Ne(v)
                        | Bound::Compatible(v) => {
                            versions.push(v.clone());
                            if let Ok(bumped) = Version::parse(&format!("{}.999999", v.as_str())) {
                                versions.push(bumped);
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        for s in &["0.0.1", "999.999.999"] {
            if let Ok(v) = Version::parse(s) {
                versions.push(v);
            }
        }
        versions
    }

    /// Check if this range is empty (no versions match)
    pub fn is_empty(&self) -> bool {
        let s = self.range_str.trim();
        if s == "empty" || s == "!*" {
            return true;
        }
        if self.is_parsed && !self.bound_sets.is_empty() {
            return self
                .bound_sets
                .iter()
                .all(|bs| bs.bounds.iter().any(|b| matches!(b, Bound::None)));
        }
        false
    }
}

/// Parse a range string into a vector of BoundSets (disjunction)
fn parse_range_str(s: &str) -> Result<Vec<BoundSet>, RezCoreError> {
    if s.is_empty() || s == "*" {
        return Ok(vec![BoundSet::any()]);
    }
    if s == "empty" || s == "!*" {
        return Ok(vec![BoundSet::none()]);
    }

    // Handle rez ".." interval syntax: "1.0..2.0" = ">=1.0,<2.0"
    // Note: must check before splitting on |
    if s.contains("..") && !s.starts_with('.') {
        // Only handle if it's a simple "a..b" form (no | or other operators in the whole string)
        if let Some(dot_pos) = s.find("..") {
            let left = &s[..dot_pos];
            let right = &s[dot_pos + 2..];
            // Both sides must look like version strings (not empty operators)
            if !left.is_empty()
                && !right.is_empty()
                && !left.starts_with('>')
                && !left.starts_with('<')
                && !left.starts_with('=')
                && !left.starts_with('!')
                && !left.starts_with('~')
            {
                // "left..right" -> ">=left,<right"
                let new_s = format!(">={},<{}", left.trim(), right.trim());
                return parse_range_str(&new_s);
            }
        }
    }

    // Split on | for OR (union)
    let or_parts: Vec<&str> = s.split('|').collect();
    let mut result = Vec::new();

    for or_part in or_parts {
        let bound_set = parse_conjunction(or_part.trim())?;
        result.push(bound_set);
    }

    Ok(result)
}

/// Parse a conjunction of constraints (AND semantics)
/// Supports: `>=1.0,<2.0` (comma) or `>=1.0 <2.0` (space) or `1.0+<2.0` (rez syntax)
fn parse_conjunction(s: &str) -> Result<BoundSet, RezCoreError> {
    if s.is_empty() || s == "*" {
        return Ok(BoundSet::any());
    }

    // Handle rez shorthand: "1.0+" = ">=1.0"
    // Handle rez shorthand: "1.0+<2.0" = ">=1.0,<2.0"
    // The `+` in rez means "this version and above", with optional upper bound after it
    let s = if s.contains('+')
        && !s.starts_with('>')
        && !s.starts_with('<')
        && !s.starts_with('=')
        && !s.starts_with('!')
        && !s.starts_with('~')
    {
        // Find the + and split: "1.0+<2.0" -> prefix="1.0", suffix="<2.0"
        if let Some(plus_pos) = s.find('+') {
            let prefix = &s[..plus_pos];
            let suffix = &s[plus_pos + 1..];
            if suffix.is_empty() {
                // "1.0+" -> ">=1.0"
                format!(">={}", prefix)
            } else {
                // "1.0+<2.0" -> ">=1.0,<2.0"
                format!(">={},{}", prefix, suffix)
            }
        } else {
            s.to_string()
        }
    } else {
        s.to_string()
    };

    let mut bounds = Vec::new();

    // Split on commas first, then spaces that separate constraints
    let parts = split_constraint_parts(&s);

    for part in parts {
        let part = part.trim();
        if part.is_empty() {
            continue;
        }
        let bound = parse_single_constraint(part)?;
        bounds.push(bound);
    }

    if bounds.is_empty() {
        return Ok(BoundSet::any());
    }

    Ok(BoundSet { bounds })
}

/// Split a string into individual constraint parts (handles comma and space separators)
fn split_constraint_parts(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();

    for ch in s.chars() {
        if ch == ',' {
            if !current.trim().is_empty() {
                parts.push(current.trim().to_string());
            }
            current = String::new();
        } else {
            current.push(ch);
        }
    }
    if !current.trim().is_empty() {
        parts.push(current.trim().to_string());
    }

    // Further split space-separated constraints within each part
    let mut final_parts = Vec::new();
    for part in parts {
        let space_parts = split_on_operator_boundaries(&part);
        final_parts.extend(space_parts);
    }

    final_parts
}

/// Split on spaces that are followed by an operator (>=, <=, >, <, ==, !=, ~=)
fn split_on_operator_boundaries(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();

    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        let ch = chars[i];
        if ch == ' ' {
            // Check if next non-space char starts an operator
            let mut j = i + 1;
            while j < chars.len() && chars[j] == ' ' {
                j += 1;
            }
            if j < chars.len() {
                let next = chars[j];
                if next == '>' || next == '<' || next == '=' || next == '!' || next == '~' {
                    if !current.trim().is_empty() {
                        parts.push(current.trim().to_string());
                    }
                    current = String::new();
                    i = j;
                    continue;
                }
            }
            current.push(ch);
        } else {
            current.push(ch);
        }
        i += 1;
    }
    if !current.trim().is_empty() {
        parts.push(current.trim().to_string());
    }
    parts
}

/// Parse a single constraint like `>=1.0`, `<2.0`, `==1.5`, `!=1.0`, `~=1.4`
fn parse_single_constraint(s: &str) -> Result<Bound, RezCoreError> {
    let s = s.trim();

    if s.is_empty() || s == "*" {
        return Ok(Bound::Any);
    }

    // Try two-char operators first
    if let Some(rest) = s.strip_prefix(">=") {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Ge(v));
    }
    if let Some(rest) = s.strip_prefix("<=") {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Le(v));
    }
    if let Some(rest) = s.strip_prefix("==") {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Eq(v));
    }
    if let Some(rest) = s.strip_prefix("!=") {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Ne(v));
    }
    if let Some(rest) = s.strip_prefix("~=") {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Compatible(v));
    }

    // Single-char operators
    if let Some(rest) = s.strip_prefix('>') {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Gt(v));
    }
    if let Some(rest) = s.strip_prefix('<') {
        let v = Version::parse(rest.trim()).map_err(|e| {
            RezCoreError::VersionRange(format!("Invalid version in range '{}': {}", s, e))
        })?;
        return Ok(Bound::Lt(v));
    }

    // No operator - treat as exact version (rez: bare version = "==version")
    let v = Version::parse(s).map_err(|e| {
        RezCoreError::VersionRange(format!("Invalid version constraint '{}': {}", s, e))
    })?;
    Ok(Bound::Eq(v))
}

/// Check if a single BoundSet is satisfiable (not trivially empty due to conflicting bounds)
fn is_bound_set_satisfiable(bs: &BoundSet) -> bool {
    // Check for None bounds
    if bs.bounds.iter().any(|b| matches!(b, Bound::None)) {
        return false;
    }
    // Extract lower and upper bounds to check for contradiction
    let mut lower: Option<(&Version, bool)> = None; // (version, inclusive)
    let mut upper: Option<(&Version, bool)> = None; // (version, inclusive)

    for bound in &bs.bounds {
        match bound {
            Bound::Any => {}
            Bound::None => return false,
            Bound::Ge(v) => match lower {
                None => lower = Some((v, true)),
                Some((lv, linc)) => {
                    if v > lv || (v == lv && !linc) {
                        lower = Some((v, true));
                    }
                }
            },
            Bound::Gt(v) => match lower {
                None => lower = Some((v, false)),
                Some((lv, _)) => {
                    if v >= lv {
                        lower = Some((v, false));
                    }
                }
            },
            Bound::Le(v) => match upper {
                None => upper = Some((v, true)),
                Some((uv, uinc)) => {
                    if v < uv || (v == uv && !uinc) {
                        upper = Some((v, true));
                    }
                }
            },
            Bound::Lt(v) => match upper {
                None => upper = Some((v, false)),
                Some((uv, _)) => {
                    if v <= uv {
                        upper = Some((v, false));
                    }
                }
            },
            Bound::Eq(v) => {
                // Equality constraint acts as both lower and upper bound
                match lower {
                    None => lower = Some((v, true)),
                    Some((lv, linc)) => {
                        if v > lv || (v == lv && !linc) {
                            lower = Some((v, true));
                        } else if v < lv {
                            // v must be >= lv but eq requires v exactly — contradiction
                            return false;
                        }
                    }
                }
                match upper {
                    None => upper = Some((v, true)),
                    Some((uv, uinc)) => {
                        if v < uv || (v == uv && !uinc) {
                            upper = Some((v, true));
                        } else if v > uv {
                            return false;
                        }
                    }
                }
            }
            Bound::Ne(_) | Bound::Compatible(_) => {}
        }
    }

    // Check if lower and upper bounds are compatible
    if let (Some((lv, linc)), Some((uv, uinc))) = (lower, upper) {
        match lv.cmp(uv) {
            std::cmp::Ordering::Greater => return false,
            std::cmp::Ordering::Equal => {
                if !linc || !uinc {
                    return false;
                }
            }
            std::cmp::Ordering::Less => {}
        }
    }

    true
}

/// Check if two BoundSets can simultaneously be satisfied (have intersection)
fn bound_sets_intersect(a: &BoundSet, b: &BoundSet) -> bool {
    // Quick check: if either is Any, they intersect
    let a_any = a.bounds.iter().all(|bnd| matches!(bnd, Bound::Any));
    let b_any = b.bounds.iter().all(|bnd| matches!(bnd, Bound::Any));
    if a_any || b_any {
        return true;
    }

    // Combine all bounds and check for structural impossibilities
    let combined_bounds: Vec<&Bound> = a.bounds.iter().chain(b.bounds.iter()).collect();

    // Check for obvious impossibilities: Eq(v) and Eq(w) where v != w
    let eq_versions: Vec<&Version> = combined_bounds
        .iter()
        .filter_map(|b| if let Bound::Eq(v) = b { Some(v) } else { None })
        .collect();
    if eq_versions.len() > 1 {
        let first = eq_versions[0];
        if eq_versions.iter().any(|v| *v != first) {
            return false;
        }
    }

    // Compute effective lower and upper bounds from combined set
    // Lower bound: maximum of all lower bounds (most restrictive)
    // Upper bound: minimum of all upper bounds (most restrictive)
    let mut lower: Option<(&Version, bool)> = None; // (version, inclusive)
    let mut upper: Option<(&Version, bool)> = None; // (version, inclusive)

    for bound in &combined_bounds {
        match bound {
            Bound::Ge(v) => match lower {
                None => lower = Some((v, true)),
                Some((lv, linc)) => {
                    if v > lv || (v == lv && !linc) {
                        lower = Some((v, true));
                    }
                }
            },
            Bound::Gt(v) => match lower {
                None => lower = Some((v, false)),
                Some((lv, _linc)) => {
                    if v >= lv {
                        lower = Some((v, false));
                    }
                }
            },
            Bound::Le(v) => match upper {
                None => upper = Some((v, true)),
                Some((uv, uinc)) => {
                    if v < uv || (v == uv && !uinc) {
                        upper = Some((v, true));
                    }
                }
            },
            Bound::Lt(v) => match upper {
                None => upper = Some((v, false)),
                Some((uv, _uinc)) => {
                    if v <= uv {
                        upper = Some((v, false));
                    }
                }
            },
            _ => {}
        }
    }

    // Check if lower bound and upper bound are compatible
    if let (Some((lv, linc)), Some((uv, uinc))) = (lower, upper) {
        match lv.cmp(uv) {
            std::cmp::Ordering::Greater => return false,
            std::cmp::Ordering::Equal => {
                // Equal bounds only feasible if both inclusive
                if !linc || !uinc {
                    return false;
                }
            }
            std::cmp::Ordering::Less => {} // feasible
        }
    }

    true
}