use core::cmp::Ordering;
use core::fmt;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VersionId(String);
impl VersionId {
#[must_use]
pub fn new(v: impl Into<String>) -> Self {
Self(v.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<String> for VersionId {
fn from(v: String) -> Self {
Self(v)
}
}
impl From<&str> for VersionId {
fn from(v: &str) -> Self {
Self(v.to_owned())
}
}
impl fmt::Display for VersionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum PostgresProvider {
Icu,
Libc,
C,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct PostgresCollation {
provider: PostgresProvider,
locale: String,
deterministic: bool,
version: VersionId,
rules: Option<String>,
encoding: String,
}
impl PostgresCollation {
#[must_use]
pub fn c() -> Self {
Self {
provider: PostgresProvider::C,
locale: String::new(),
deterministic: true,
version: VersionId::new("c"),
rules: None,
encoding: "UTF8".to_owned(),
}
}
#[must_use]
pub fn icu(locale: impl Into<String>, deterministic: bool, version: VersionId) -> Self {
Self {
provider: PostgresProvider::Icu,
locale: locale.into(),
deterministic,
version,
rules: None,
encoding: "UTF8".to_owned(),
}
}
#[must_use]
pub fn libc(locale: impl Into<String>) -> Self {
Self {
provider: PostgresProvider::Libc,
locale: locale.into(),
deterministic: true,
version: VersionId::new("libc"),
rules: None,
encoding: "UTF8".to_owned(),
}
}
#[must_use]
pub fn with_rules(mut self, rules: impl Into<String>) -> Self {
self.rules = Some(rules.into());
self
}
#[must_use]
pub fn with_encoding(mut self, encoding: impl Into<String>) -> Self {
self.encoding = encoding.into();
self
}
#[must_use]
pub const fn provider(&self) -> PostgresProvider {
self.provider
}
#[must_use]
pub fn locale(&self) -> &str {
&self.locale
}
#[must_use]
pub const fn deterministic(&self) -> bool {
self.deterministic
}
#[must_use]
pub const fn version(&self) -> &VersionId {
&self.version
}
#[must_use]
pub fn rules(&self) -> Option<&str> {
self.rules.as_deref()
}
#[must_use]
pub fn encoding(&self) -> &str {
&self.encoding
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum MysqlUcaVersion {
Uca400,
Uca900,
}
impl MysqlUcaVersion {
#[must_use]
pub fn version_id(self) -> VersionId {
match self {
Self::Uca400 => VersionId::new("4.0.0"),
Self::Uca900 => VersionId::new("9.0.0"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Pad {
NoPad,
Space,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct MysqlCollation {
pub name: String,
pub uca_version: MysqlUcaVersion,
pub pad: Pad,
}
impl MysqlCollation {
#[must_use]
pub fn new(name: impl Into<String>, uca_version: MysqlUcaVersion, pad: Pad) -> Self {
Self {
name: name.into(),
uca_version,
pad,
}
}
#[must_use]
pub fn utf8mb4_0900_ai_ci() -> Self {
Self {
name: "utf8mb4_0900_ai_ci".to_owned(),
uca_version: MysqlUcaVersion::Uca900,
pad: Pad::NoPad,
}
}
#[must_use]
pub fn utf8mb4_unicode_ci() -> Self {
Self {
name: "utf8mb4_unicode_ci".to_owned(),
uca_version: MysqlUcaVersion::Uca400,
pad: Pad::Space,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum OracleProvider {
Binary,
Uca,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum OracleUcaVersion {
Uca700,
Uca1210,
}
impl OracleUcaVersion {
#[must_use]
pub fn version_id(self) -> VersionId {
match self {
Self::Uca700 => VersionId::new("7.0.0"),
Self::Uca1210 => VersionId::new("12.1.0"),
}
}
#[must_use]
pub const fn collation_name(self) -> &'static str {
match self {
Self::Uca700 => "UCA0700_DUCET",
Self::Uca1210 => "UCA1210_DUCET",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct OracleCollation {
provider: OracleProvider,
nls_sort: String,
uca_version: Option<OracleUcaVersion>,
charset: String,
blank_padded: bool,
}
impl OracleCollation {
#[must_use]
pub fn binary() -> Self {
Self {
provider: OracleProvider::Binary,
nls_sort: "BINARY".to_owned(),
uca_version: None,
charset: "AL32UTF8".to_owned(),
blank_padded: false,
}
}
#[must_use]
pub fn uca_ducet(version: OracleUcaVersion) -> Self {
Self {
provider: OracleProvider::Uca,
nls_sort: version.collation_name().to_owned(),
uca_version: Some(version),
charset: "AL32UTF8".to_owned(),
blank_padded: false,
}
}
#[must_use]
pub fn from_nls_sort(nls_sort: impl Into<String>, charset: impl Into<String>) -> Self {
let name = nls_sort.into().trim().to_ascii_uppercase();
let (provider, uca_version) = match name.as_str() {
"UCA0700_DUCET" => (OracleProvider::Uca, Some(OracleUcaVersion::Uca700)),
"UCA1210_DUCET" => (OracleProvider::Uca, Some(OracleUcaVersion::Uca1210)),
_ => (OracleProvider::Binary, None),
};
Self {
provider,
nls_sort: name,
uca_version,
charset: charset.into(),
blank_padded: false,
}
}
#[must_use]
pub fn with_blank_padded(mut self, blank_padded: bool) -> Self {
self.blank_padded = blank_padded;
self
}
#[must_use]
pub const fn provider(&self) -> OracleProvider {
self.provider
}
#[must_use]
pub fn nls_sort(&self) -> &str {
&self.nls_sort
}
#[must_use]
pub const fn uca_version(&self) -> Option<OracleUcaVersion> {
self.uca_version
}
#[must_use]
pub fn charset(&self) -> &str {
&self.charset
}
#[must_use]
pub const fn blank_padded(&self) -> bool {
self.blank_padded
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Backend {
Binary,
PostgresIcu(PostgresCollation),
MysqlUca(MysqlCollation),
Oracle(OracleCollation),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "Backend", into = "Backend"))]
pub struct Collation {
backend: Backend,
}
#[cfg(feature = "serde")]
impl TryFrom<Backend> for Collation {
type Error = Error;
fn try_from(backend: Backend) -> Result<Self> {
Self::from_backend(backend)
}
}
#[cfg(feature = "serde")]
impl From<Collation> for Backend {
fn from(collation: Collation) -> Self {
collation.backend
}
}
impl Collation {
#[must_use]
pub const fn binary() -> Self {
Self {
backend: Backend::Binary,
}
}
#[must_use]
pub const fn postgres_c() -> Self {
Self::binary()
}
pub fn postgres_icu(
locale: impl Into<String>,
deterministic: bool,
source_version: VersionId,
) -> Result<Self> {
let spec = PostgresCollation::icu(locale, deterministic, source_version);
Self::postgres(spec)
}
#[allow(clippy::needless_pass_by_value)]
pub fn postgres(spec: PostgresCollation) -> Result<Self> {
if !spec.encoding().eq_ignore_ascii_case("UTF8") {
return Err(Error::unsupported(
"postgres",
spec.locale(),
"only UTF-8 sources are reproducible; other encodings are refused",
));
}
if spec.rules().is_some() {
return Err(Error::unsupported(
"postgres",
spec.locale(),
"custom ICU collation rules (collicurules) are not reproducible",
));
}
match spec.provider() {
PostgresProvider::C => Ok(Self::binary()),
PostgresProvider::Libc => {
let locale = spec.locale();
if locale.eq_ignore_ascii_case("C") || locale.eq_ignore_ascii_case("POSIX") {
Ok(Self::binary())
} else {
Err(Error::unsupported(
"postgres",
locale,
"libc collations other than C/POSIX are not reproducible portably",
))
}
}
PostgresProvider::Icu => {
#[cfg(feature = "postgres-icu")]
{
crate::postgres::validate(&spec)?;
Ok(Self {
backend: Backend::PostgresIcu(spec),
})
}
#[cfg(not(feature = "postgres-icu"))]
{
let _ = spec;
Err(Error::FeatureDisabled {
feature: "postgres-icu",
})
}
}
}
}
#[cfg(feature = "mysql-uca")]
#[must_use]
pub fn mysql_0900_ai_ci() -> Self {
Self::mysql(MysqlCollation::utf8mb4_0900_ai_ci()).expect("utf8mb4_0900_ai_ci is supported")
}
#[cfg(feature = "mysql-uca")]
#[must_use]
pub fn mysql_unicode_ci() -> Self {
Self::mysql(MysqlCollation::utf8mb4_unicode_ci()).expect("utf8mb4_unicode_ci is supported")
}
#[allow(clippy::needless_pass_by_value)]
pub fn mysql(spec: MysqlCollation) -> Result<Self> {
#[cfg(feature = "mysql-uca")]
{
crate::mysql::validate(&spec)?;
Ok(Self {
backend: Backend::MysqlUca(spec),
})
}
#[cfg(not(feature = "mysql-uca"))]
{
let _ = spec;
Err(Error::FeatureDisabled {
feature: "mysql-uca",
})
}
}
#[allow(clippy::needless_pass_by_value)]
pub fn oracle(spec: OracleCollation) -> Result<Self> {
#[cfg(feature = "oracle")]
{
Ok(Self {
backend: crate::oracle::validate(&spec)?,
})
}
#[cfg(not(feature = "oracle"))]
{
let _ = spec;
Err(Error::FeatureDisabled { feature: "oracle" })
}
}
pub fn from_mysql_name_unspecified_version(name: &str) -> Result<Self> {
match name {
"utf8mb4_0900_ai_ci" => Self::mysql(MysqlCollation::utf8mb4_0900_ai_ci()),
"utf8mb4_unicode_ci" => Self::mysql(MysqlCollation::utf8mb4_unicode_ci()),
"utf8mb4_0900_bin" => Ok(Self::binary()),
_ => Err(Error::unsupported(
"mysql",
name,
"unrecognised or version-dependent collation; resolve it explicitly",
)),
}
}
#[must_use]
pub const fn backend(&self) -> &Backend {
&self.backend
}
pub fn compare(&self, a: &str, b: &str) -> Result<Ordering> {
match &self.backend {
Backend::Binary => Ok(a.as_bytes().cmp(b.as_bytes())),
#[cfg(feature = "postgres-icu")]
Backend::PostgresIcu(spec) => crate::postgres::compare(spec, a, b),
#[cfg(not(feature = "postgres-icu"))]
Backend::PostgresIcu(_) => unreachable!("postgres backend cannot be constructed"),
#[cfg(feature = "mysql-uca")]
Backend::MysqlUca(spec) => Ok(crate::mysql::compare(spec, a, b)),
#[cfg(not(feature = "mysql-uca"))]
Backend::MysqlUca(_) => unreachable!("mysql backend cannot be constructed"),
#[cfg(feature = "oracle-uca")]
Backend::Oracle(spec) => crate::oracle::compare(spec, a, b),
#[cfg(not(feature = "oracle-uca"))]
Backend::Oracle(_) => unreachable!("oracle backend cannot be constructed"),
}
}
pub fn equal(&self, a: &str, b: &str) -> Result<bool> {
Ok(self.compare(a, b)? == Ordering::Equal)
}
pub fn from_backend(backend: Backend) -> Result<Self> {
match backend {
Backend::Binary => Ok(Self::binary()),
Backend::PostgresIcu(spec) => Self::postgres(spec),
Backend::MysqlUca(spec) => Self::mysql(spec),
Backend::Oracle(spec) => Self::oracle(spec),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_is_bytewise() {
let c = Collation::binary();
assert_eq!(c.compare("a", "b").unwrap(), Ordering::Less);
assert_eq!(c.compare("A", "a").unwrap(), Ordering::Less);
assert!(c.equal("a", "a").unwrap());
}
#[test]
fn test_postgres_libc_is_refused() {
let spec = PostgresCollation::libc("en_US.UTF-8");
assert!(Collation::postgres(spec).is_err());
}
#[test]
fn test_postgres_libc_c_is_binary() {
for locale in ["C", "POSIX", "posix"] {
let spec = PostgresCollation::libc(locale);
let c = Collation::postgres(spec).unwrap();
assert!(matches!(c.backend(), Backend::Binary), "{locale}");
}
}
#[test]
fn test_unspecified_mysql_name_unknown_is_refused() {
assert!(Collation::from_mysql_name_unspecified_version("utf8mb4_general_ci").is_err());
assert!(Collation::from_mysql_name_unspecified_version("utf8mb4_zh_0900_as_cs").is_err());
}
#[test]
fn test_collation_is_send_sync() {
static_assertions::assert_impl_all!(Collation: Send, Sync);
}
#[test]
fn test_error_is_fallback() {
let e = Error::unsupported("mysql", "x", "y");
assert!(e.is_fallback_required());
}
}