use core::cmp::Ordering;
use std::ffi::CString;
use rust_icu_sys as sys;
use rust_icu_sys::versioned_function;
use rust_icu_ucol::UCollator;
use crate::error::{Error, Result};
use crate::spec::PostgresCollation;
use crate::thread_local;
#[allow(unsafe_code)]
fn local_collversion(locale: &str) -> Option<String> {
let c_locale = CString::new(locale).ok()?;
let mut status: sys::UErrorCode = sys::UErrorCode::U_ZERO_ERROR;
let coll = unsafe { versioned_function!(ucol_open)(c_locale.as_ptr(), &raw mut status) };
if status > sys::UErrorCode::U_ZERO_ERROR || coll.is_null() {
return None;
}
let mut info = [0u8; 4];
let mut buf: [core::ffi::c_char; 20] = [0; 20];
unsafe {
versioned_function!(ucol_getVersion)(coll, info.as_mut_ptr());
versioned_function!(ucol_close)(coll);
versioned_function!(u_versionToString)(info.as_mut_ptr(), buf.as_mut_ptr());
}
let len = buf.iter().position(|&c| c == 0)?;
let bytes = buf[..len]
.iter()
.map(|&c| u8::try_from(c).ok())
.collect::<Option<Vec<u8>>>()?;
String::from_utf8(bytes).ok()
}
#[must_use]
#[allow(unsafe_code)]
pub fn icu_library_version() -> String {
let mut bytes = [0u8; 4];
unsafe { versioned_function!(u_getVersion)(bytes.as_mut_ptr()) };
let [major, minor, _, _] = bytes;
format!("{major}.{minor}")
}
#[must_use]
pub fn collation_version(locale: &str) -> Option<String> {
local_collversion(locale)
}
pub(crate) fn validate(spec: &PostgresCollation) -> Result<()> {
let locale = spec.locale();
if locale.is_empty() {
return Err(Error::unsupported(
"postgres",
locale,
"ICU collation requires a non-empty locale id",
));
}
UCollator::try_from(locale).map_err(|_| {
Error::unsupported(
"postgres",
locale,
"ICU could not open this locale on this system",
)
})?;
let Some(local) = local_collversion(locale) else {
return Err(Error::unsupported(
"postgres",
locale,
"ICU could not report a collation version for this locale",
));
};
let source = spec.version().as_str();
if source.is_empty() || source == "unknown" {
return Err(Error::unsupported(
"postgres",
locale,
"an exact ICU collation version is required; empty or unknown is not accepted",
));
}
if !version_matches(source, &local) {
return Err(Error::VersionMismatch {
source: spec.version().clone(),
local: crate::spec::VersionId::new(local),
});
}
Ok(())
}
fn version_matches(source: &str, local: &str) -> bool {
fn components(v: &str) -> Option<Vec<u8>> {
let mut out = Vec::new();
for part in v.split('.') {
out.push(part.parse::<u8>().ok()?);
}
if out.is_empty() || out.len() > 4 {
return None;
}
while out.len() > 1 && out.last() == Some(&0) {
out.pop();
}
Some(out)
}
match (components(source), components(local)) {
(Some(a), Some(b)) => a == b,
_ => source == local,
}
}
pub(crate) fn compare(spec: &PostgresCollation, a: &str, b: &str) -> Result<Ordering> {
let unsupported = || {
Error::unsupported(
"postgres",
spec.locale(),
"ICU string comparison failed at runtime",
)
};
let ord = thread_local::with(spec.locale(), |collator| collator.strcoll_utf8(a, b))
.ok_or_else(unsupported)?
.map_err(|_| unsupported())?;
if ord == Ordering::Equal && spec.deterministic() {
Ok(a.as_bytes().cmp(b.as_bytes()))
} else {
Ok(ord)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::spec::VersionId;
#[test]
fn test_empty_locale_is_refused() {
let spec = PostgresCollation::icu(String::new(), true, VersionId::new("x"));
assert!(validate(&spec).is_err());
}
#[test]
fn test_version_matches_normalizes_only_trailing_zeros() {
assert!(version_matches("153.128", "153.128.0"));
assert!(version_matches("153.128", "153.128"));
assert!(version_matches("153.14", "153.14.0.0"));
assert!(!version_matches("153.128", "153.14"));
assert!(!version_matches("153.128", "152.1"));
assert!(!version_matches("153.136.999", "153.136.48"));
assert!(!version_matches("153.136.48", "153.136.999"));
}
#[test]
fn test_version_gate_refuses_nonzero_tail_mismatch() {
let spec = PostgresCollation::icu("und", true, VersionId::new("153.136.999"));
assert!(validate(&spec).is_err());
}
#[test]
fn test_version_gate_refuses_empty_and_unknown() {
for v in ["", "unknown"] {
let spec = PostgresCollation::icu("und", true, VersionId::new(v));
let err = validate(&spec).unwrap_err();
assert!(err.is_fallback_required(), "version {v:?} must be refused");
}
}
#[test]
fn test_local_collversion_reproduces_postgres_format() {
let v = local_collversion("und").expect("und collation version");
let parts: Vec<&str> = v.split('.').collect();
assert_eq!(parts.len(), 2, "unexpected version shape: {v}");
assert_eq!(parts[0], "153", "unexpected UCOL major: {v}");
assert!(
parts[1].parse::<u32>().is_ok(),
"non-numeric UCA version: {v}"
);
}
#[test]
fn test_tailored_locale_adds_component() {
if let Some(base) = local_collversion("und") {
let base_parts = base.split('.').count();
if let Some(v) = local_collversion("de-u-co-phonebk") {
assert!(
v.split('.').count() > base_parts,
"tailored version {v} should have more components than base {base}"
);
}
}
}
#[test]
fn test_version_gate_refuses_mismatch() {
let spec = PostgresCollation::icu("und", true, VersionId::new("1.2"));
match validate(&spec) {
Err(Error::VersionMismatch { source, local }) => {
assert_eq!(source.as_str(), "1.2");
assert_ne!(local.as_str(), "");
}
other => panic!("expected VersionMismatch, got {other:?}"),
}
}
}