repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ucal/src/lib.rs | rust_icu_ucal/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Implementation of `ucal.h`.
//!
//! As a general piece of advice, since a lot of documentation is currently elided,
//! see the unit tests for example uses of each of the wrapper functions.
use {
log::trace, rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
rust_icu_sys::*, rust_icu_uenum as uenum, rust_icu_ustring as ustring, std::convert::TryFrom,
std::ffi,
};
/// Implements the UCalendar type from `ucal.h`.
///
/// The naming `rust_icu_ucal::UCalendar` is a bit repetetetitive, but makes it
/// a bit more obvious what ICU type it is wrapping.
#[derive(Debug)]
pub struct UCalendar {
// Internal representation of the UCalendar, a pointer to a C type from ICU.
//
// The representation is owned by this type, and must be deallocated by calling
// `sys::ucal_close`.
rep: *mut sys::UCalendar,
}
impl Drop for UCalendar {
/// Deallocates the internal representation of UCalendar.
///
/// Implements `ucal_close`.
fn drop(&mut self) {
unsafe {
versioned_function!(ucal_close)(self.rep);
};
}
}
impl UCalendar {
/// Creates a new UCalendar from a `UChar` zone ID.
///
/// Use `new` to construct this from rust types only.
fn new_from_uchar(
zone_id: &ustring::UChar,
locale: &str,
cal_type: sys::UCalendarType,
) -> Result<UCalendar, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz_locale = ffi::CString::new(locale).map_err(common::Error::wrapper)?;
// Requires that zone_id contains a valid Unicode character representation with known
// beginning and length. asciiz_locale must be a pointer to a valid C string. The first
// condition is assumed to be satisfied by ustring::UChar, and the second should be
// satisfied by construction of asciiz_locale just above.
let raw_ucal = unsafe {
versioned_function!(ucal_open)(
zone_id.as_c_ptr(),
zone_id.len() as i32,
asciiz_locale.as_ptr(),
cal_type,
&mut status,
) as *mut sys::UCalendar
};
common::Error::ok_or_warning(status)?;
Ok(UCalendar { rep: raw_ucal })
}
/// Creates a new UCalendar.
///
/// Implements `ucal_open`.
pub fn new(
zone_id: &str,
locale: &str,
cal_type: sys::UCalendarType,
) -> Result<UCalendar, common::Error> {
let zone_id_uchar = ustring::UChar::try_from(zone_id)?;
Self::new_from_uchar(&zone_id_uchar, locale, cal_type)
}
/// Returns this UCalendar's internal C representation. Use only for interfacing with the C
/// low-level API.
pub fn as_c_calendar(&self) -> *const sys::UCalendar {
self.rep
}
/// Sets the calendar's current date/time in milliseconds since the epoch.
///
/// Implements `ucal_setMillis`.
pub fn set_millis(&mut self, date_time: sys::UDate) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
versioned_function!(ucal_setMillis)(self.rep, date_time, &mut status);
};
common::Error::ok_or_warning(status)
}
/// Gets the calendar's current date/time in milliseconds since the epoch.
///
/// Implements `ucal_getMillis`.
pub fn get_millis(&self) -> Result<sys::UDate, common::Error> {
let mut status = common::Error::OK_CODE;
let millis = unsafe { versioned_function!(ucal_getMillis)(self.rep, &mut status) };
common::Error::ok_or_warning(status)?;
Ok(millis)
}
/// Sets the calendar's current date in the calendar's local time zone.
///
/// Note that `month` is 0-based.
///
/// Implements `ucal_setDate`.
pub fn set_date(&mut self, year: i32, month: i32, date: i32) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
versioned_function!(ucal_setDate)(self.rep, year, month, date, &mut status);
}
common::Error::ok_or_warning(status)?;
Ok(())
}
/// Sets the calendar's current date and time in the calendar's local time zone.
///
/// Note that `month` is 0-based.
///
/// Implements `ucal_setDateTime`.
pub fn set_date_time(
&mut self,
year: i32,
month: i32,
date: i32,
hour: i32,
minute: i32,
second: i32,
) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
versioned_function!(ucal_setDateTime)(
self.rep,
year,
month,
date,
hour,
minute,
second,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
Ok(())
}
/// Returns the calendar's time zone's offset from UTC in milliseconds, for the calendar's
/// current date/time.
///
/// This does not include the daylight savings offset, if any. Note that the calendar's current
/// date/time is significant because time zones are occasionally redefined -- a time zone that
/// has a +16.5 hour offset today might have had a +17 hour offset a decade ago.
///
/// Wraps `ucal_get` for `UCAL_ZONE_OFFSET`.
pub fn get_zone_offset(&self) -> Result<i32, common::Error> {
self.get(UCalendarDateFields::UCAL_ZONE_OFFSET)
}
/// Returns the calendar's daylight savings offset from its non-DST time, in milliseconds, for
/// the calendar's current date/time. This may be 0 if the time zone does not observe DST at
/// all, or if the time zone is not in the daylight savings period at the calendar's current
/// date/time.
///
/// Wraps `ucal_get` for `UCAL_ZONE_DST_OFFSET`.
pub fn get_dst_offset(&self) -> Result<i32, common::Error> {
self.get(UCalendarDateFields::UCAL_DST_OFFSET)
}
/// Returns true if the calendar is currently in daylight savings / summer time.
///
/// Implements `ucal_inDaylightTime`.
pub fn in_daylight_time(&self) -> Result<bool, common::Error> {
let mut status = common::Error::OK_CODE;
let in_daylight_time: sys::UBool =
unsafe { versioned_function!(ucal_inDaylightTime)(self.as_c_calendar(), &mut status) };
common::Error::ok_or_warning(status)?;
Ok(in_daylight_time != 0)
}
/// Implements `ucal_get`.
///
/// Consider using specific higher-level methods instead.
pub fn get(&self, field: UCalendarDateFields) -> Result<i32, common::Error> {
let mut status: UErrorCode = common::Error::OK_CODE;
let value =
unsafe { versioned_function!(ucal_get)(self.as_c_calendar(), field, &mut status) };
common::Error::ok_or_warning(status)?;
Ok(value)
}
}
/// Implements `ucal_setDefaultTimeZone`
pub fn set_default_time_zone(zone_id: &str) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
let mut zone_id_uchar = ustring::UChar::try_from(zone_id)?;
zone_id_uchar.make_z();
// Requires zone_id_uchar to be a valid pointer until the function returns.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_setDefaultTimeZone)(zone_id_uchar.as_c_ptr(), &mut status);
};
common::Error::ok_or_warning(status)
}
/// Implements `ucal_getDefaultTimeZone`
pub fn get_default_time_zone() -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
// Preflight the time zone first.
let time_zone_length = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_getDefaultTimeZone)(std::ptr::null_mut(), 0, &mut status)
} as usize;
common::Error::ok_preflight(status)?;
// Should this capacity include the terminating \u{0}?
let mut status = common::Error::OK_CODE;
let mut uchar = ustring::UChar::new_with_capacity(time_zone_length);
trace!("length: {}", time_zone_length);
// Requires that uchar is a valid buffer. Should be guaranteed by the constructor above.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_getDefaultTimeZone)(
uchar.as_mut_c_ptr(),
time_zone_length as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
trace!("result: {:?}", uchar);
String::try_from(&uchar)
}
/// Implements `ucal_getTZDataVersion`
pub fn get_tz_data_version() -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
let tz_data_version = unsafe {
let raw_cstring = versioned_function!(ucal_getTZDataVersion)(&mut status);
common::Error::ok_or_warning(status)?;
ffi::CStr::from_ptr(raw_cstring)
.to_string_lossy()
.into_owned()
};
Ok(tz_data_version)
}
/// Gets the current date and time, in milliseconds since the Epoch.
///
/// Implements `ucal_getNow`.
pub fn get_now() -> f64 {
unsafe { versioned_function!(ucal_getNow)() as f64 }
}
/// Opens a list of available time zones for the given country.
///
/// Implements `ucal_openCountryTimeZones`.
pub fn country_time_zones(country: &str) -> Result<uenum::Enumeration, common::Error> {
uenum::ucal_open_country_time_zones(country)
}
/// Opens a list of available time zone IDs with the given filters.
///
/// Implements `ucal_openTimeZoneIDEnumeration`
pub fn time_zone_id_enumeration(
zone_type: sys::USystemTimeZoneType,
region: Option<&str>,
raw_offset: Option<i32>,
) -> Result<uenum::Enumeration, common::Error> {
uenum::ucal_open_time_zone_id_enumeration(zone_type, region, raw_offset)
}
/// Opens a list of available time zones.
///
/// Implements `ucal_openTimeZones`
pub fn time_zones() -> Result<uenum::Enumeration, common::Error> {
uenum::open_time_zones()
}
#[cfg(test)]
mod tests {
use {
super::{UCalendar, *},
regex::Regex,
std::collections::HashSet,
};
#[test]
fn test_time_zones() {
let tz_iter = time_zones().expect("time zones opened");
assert_eq!(
tz_iter
.map(|r| { r.expect("time zone is available") })
.take(3)
.collect::<Vec<String>>(),
vec!["ACT", "AET", "AGT"]
);
}
#[test]
fn test_time_zone_id_enumeration_no_filters() {
let tz_iter =
time_zone_id_enumeration(sys::USystemTimeZoneType::UCAL_ZONE_TYPE_ANY, None, None)
.expect("time_zone_id_enumeration() opened");
let from_enumeration = tz_iter
.map(|r| r.expect("timezone is available"))
.collect::<Vec<String>>();
let from_time_zones = time_zones()
.expect("time_zones() opened")
.map(|r| r.expect("time zone is available"))
.collect::<Vec<String>>();
assert!(!from_time_zones.is_empty());
assert_eq!(from_enumeration, from_time_zones);
}
#[test]
fn test_time_zone_id_enumeration_by_type_region() {
let tz_iter = time_zone_id_enumeration(
sys::USystemTimeZoneType::UCAL_ZONE_TYPE_CANONICAL,
Some("us"),
None,
)
.expect("time_zone_id_enumeration() opened");
assert_eq!(
tz_iter
.map(|r| { r.expect("time zone is available") })
.take(3)
.collect::<Vec<String>>(),
vec!["America/Adak", "America/Anchorage", "America/Boise"]
);
}
#[test]
fn test_time_zone_id_enumeration_by_offset() {
let tz_iter = time_zone_id_enumeration(
sys::USystemTimeZoneType::UCAL_ZONE_TYPE_ANY,
None,
Some(0), /* GMT */
)
.expect("time_zone_id_enumeration() opened");
let tz_ids = tz_iter
.map(|r| r.expect("time zone is available"))
.collect::<HashSet<String>>();
assert!(tz_ids.contains("UTC"));
assert!(!tz_ids.contains("Etc/GMT-1"));
}
#[test]
fn test_country_time_zones() {
let tz_iter = country_time_zones("us").expect("time zones available");
assert_eq!(
tz_iter
.map(|r| { r.expect("time zone is available") })
.take(3)
.collect::<Vec<String>>(),
vec!["AST", "America/Adak", "America/Anchorage"]
);
}
#[test]
fn test_default_time_zone() {
super::set_default_time_zone("America/Adak").expect("time zone set with success");
assert_eq!(
super::get_default_time_zone().expect("time zone obtained"),
"America/Adak",
);
}
#[test]
fn test_get_tz_data_version() {
let re = Regex::new(r"^[0-9][0-9][0-9][0-9][a-z][a-z0-9]*$").expect("valid regex");
let tz_version = super::get_tz_data_version().expect("get_tz_data_version works");
assert!(re.is_match(&tz_version), "version was: {:?}", &tz_version);
}
#[test]
fn test_get_set_millis() -> Result<(), common::Error> {
let now = get_now();
let mut cal = UCalendar::new("America/New_York", "en-US", UCalendarType::UCAL_GREGORIAN)?;
// Assert that the times are basically the same.
// Let's assume that no more than 1 second might elapse between the execution of `get_now()`
// and `get_millis()`.
assert!((now - cal.get_millis()?).abs() <= 1000f64);
let arbitrary_delta_ms = 17.0;
let date = now + arbitrary_delta_ms;
cal.set_millis(date)?;
assert_eq!(cal.get_millis()?, date);
Ok(())
}
#[test]
fn test_set_date() -> Result<(), common::Error> {
// Timestamps hard-coded, not parsed, to avoid cyclic dependency on udat.
// 2020-05-07T21:00:00.000-04:00
let time_a = 1588899600000f64;
// 2020-05-04T21:00:00.000-04:00
let time_b = 1588640400000f64;
let mut cal = UCalendar::new("America/New_York", "en-US", UCalendarType::UCAL_GREGORIAN)?;
cal.set_millis(time_a)?;
cal.set_date(2020, UCalendarMonths::UCAL_MAY as i32, 4)?;
assert_eq!(cal.get_millis()?, time_b);
Ok(())
}
#[test]
fn test_set_date_time() -> Result<(), common::Error> {
// Timestamps hard-coded, not parsed, to avoid cyclic dependency on udat.
// 2020-05-07T21:26:55.898-04:00
let time_a = 1588901215898f64;
// 2020-05-04T21:00:00.898-04:00
let time_b = 1588640400898f64;
let mut cal = UCalendar::new("America/New_York", "en-US", UCalendarType::UCAL_GREGORIAN)?;
cal.set_millis(time_a)?;
cal.set_date_time(2020, UCalendarMonths::UCAL_MAY as i32, 4, 21, 0, 0)?;
assert_eq!(cal.get_millis()?, time_b);
Ok(())
}
#[test]
fn test_get() -> Result<(), common::Error> {
// Timestamps hard-coded, not parsed, to avoid cyclic dependency on udat.
// 2020-05-07T21:26:55.898-04:00
let date_time = 1588901215898f64;
let mut cal = UCalendar::new("America/New_York", "en-US", UCalendarType::UCAL_GREGORIAN)?;
cal.set_millis(date_time)?;
assert_eq!(cal.get(UCalendarDateFields::UCAL_DAY_OF_MONTH)?, 7);
assert_eq!(cal.get(UCalendarDateFields::UCAL_MILLISECOND)?, 898);
Ok(())
}
#[test]
fn test_offsets_and_daylight_time() -> Result<(), common::Error> {
let mut cal = UCalendar::new("America/New_York", "en-US", UCalendarType::UCAL_GREGORIAN)?;
// -5 hours
let expected_zone_offset_ms: i32 = -5 * 60 * 60 * 1000;
// + 1 hour
let expected_dst_offset_ms: i32 = 1 * 60 * 60 * 1000;
cal.set_date_time(2020, UCalendarMonths::UCAL_MAY as i32, 7, 21, 0, 0)?;
assert_eq!(cal.get_zone_offset()?, expected_zone_offset_ms);
assert_eq!(cal.get_dst_offset()?, expected_dst_offset_ms);
assert!(cal.in_daylight_time()?);
// -5 hours
let expected_zone_offset: i32 = -5 * 60 * 60 * 1000;
// No offset
let expected_dst_offset: i32 = 0;
cal.set_date_time(2020, UCalendarMonths::UCAL_JANUARY as i32, 15, 12, 0, 0)?;
assert_eq!(cal.get_zone_offset()?, expected_zone_offset);
assert_eq!(cal.get_dst_offset()?, expected_dst_offset);
assert!(!cal.in_daylight_time()?);
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_upluralrules/src/lib.rs | rust_icu_upluralrules/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU plural rules support for Rust
//!
//! This crate provides locale-sensitive plural rules, based on the list
//! formatting as implemente by the ICU library. Specifically, the functionality
//! exposed through its C API, as available in the [header `upluralrules.h`][header].
//!
//! [header]: https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/upluralrules_8h.html
//!
//! > Are you missing some features from this crate? Consider [reporting an
//! issue](https://github.com/google/rust_icu/issues) or even [contributing the
//! functionality](https://github.com/google/rust_icu/pulls).
use {
rust_icu_common as common,
rust_icu_sys::{self as sys, versioned_function, *},
rust_icu_uenum as uenum, rust_icu_ustring as ustring,
rust_icu_ustring::buffered_uchar_method_with_retry,
std::{convert::TryFrom, convert::TryInto, ffi, ptr},
};
/// The "plural rules" formatter struct. Create a new instance with [UPluralRules::try_new], or
/// [UPluralRules::try_new_styled].
#[derive(Debug)]
pub struct UPluralRules {
// Internal representation is the low-level ICU UPluralRules struct.
rep: ptr::NonNull<sys::UPluralRules>,
}
impl Drop for UPluralRules {
/// Implements uplrules_close`.
fn drop(&mut self) {
unsafe { versioned_function!(uplrules_close)(self.rep.as_ptr()) };
}
}
impl UPluralRules {
/// Implements uplrules_open`.
pub fn try_new(locale: &str) -> Result<UPluralRules, common::Error> {
let locale_cstr = ffi::CString::new(locale)?;
let mut status = common::Error::OK_CODE;
// Unsafety note: uplrules_open is the way to open a new formatter.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(uplrules_open)(locale_cstr.as_ptr(), &mut status)
as *mut sys::UPluralRules
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UPluralRules);
Ok(UPluralRules {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Implements `uplrules_openForType`.
pub fn try_new_styled(
locale: &str,
format_type: sys::UPluralType,
) -> Result<UPluralRules, common::Error> {
let locale_cstr = ffi::CString::new(locale)?;
let mut status = common::Error::OK_CODE;
// Unsafety note: all parameters are safe, so should be valid.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(uplrules_openForType)(
locale_cstr.as_ptr(),
format_type,
&mut status,
) as *mut sys::UPluralRules
};
common::Error::ok_or_warning(status)?;
Ok(UPluralRules {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Implements `uplrules_select`.
pub fn select_ustring(&self, number: f64) -> Result<ustring::UChar, common::Error> {
const BUFFER_CAPACITY: usize = 20;
buffered_uchar_method_with_retry!(
select_impl,
BUFFER_CAPACITY,
[rep: *const sys::UPluralRules, number: f64,],
[]
);
select_impl(
versioned_function!(uplrules_select),
self.rep.as_ptr(),
number,
)
}
/// Implements `uplrules_select`.
pub fn select(&self, number: f64) -> Result<String, common::Error> {
let result = self.select_ustring(number);
match result {
Err(e) => Err(e),
Ok(u) => String::try_from(&u).map_err(|e| e.into()),
}
}
/// Implements `uplrules_getKeywords`
pub fn get_keywords(&self) -> Result<uenum::Enumeration, common::Error> {
let mut status = UErrorCode::U_ZERO_ERROR;
let raw_enum = unsafe {
assert_eq!(status, UErrorCode::U_ZERO_ERROR);
versioned_function!(uplrules_getKeywords)(self.rep.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(unsafe {
assert_ne!(raw_enum, 0 as *mut sys::UEnumeration);
uenum::Enumeration::from_raw_parts(None, raw_enum)
})
}
}
#[cfg(test)]
mod testing {
use super::*;
#[test]
fn plurals_ar_eg() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new("ar_EG").expect("locale ar_EG exists");
assert_eq!("zero", pl.select(0 as f64)?);
assert_eq!("one", pl.select(1 as f64)?);
assert_eq!("two", pl.select(2 as f64)?);
assert_eq!("few", pl.select(6 as f64)?);
assert_eq!("many", pl.select(18 as f64)?);
Ok(())
}
#[test]
fn plurals_ar_eg_styled() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new_styled("ar_EG", UPluralType::UPLURAL_TYPE_ORDINAL)
.expect("locale ar_EG exists");
assert_eq!("other", pl.select(0 as f64)?);
assert_eq!("other", pl.select(1 as f64)?);
assert_eq!("other", pl.select(2 as f64)?);
assert_eq!("other", pl.select(6 as f64)?);
assert_eq!("other", pl.select(18 as f64)?);
Ok(())
}
#[test]
fn plurals_sr_rs() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new("sr_RS").expect("locale sr_RS exists");
assert_eq!("other", pl.select(0 as f64)?);
assert_eq!("one", pl.select(1 as f64)?);
assert_eq!("few", pl.select(2 as f64)?);
assert_eq!("few", pl.select(4 as f64)?);
assert_eq!("other", pl.select(5 as f64)?);
assert_eq!("other", pl.select(6 as f64)?);
assert_eq!("other", pl.select(18 as f64)?);
assert_eq!("other", pl.select(11 as f64)?);
assert_eq!("one", pl.select(21 as f64)?);
Ok(())
}
#[test]
fn plurals_sr_rs_styled() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new_styled("sr_RS", UPluralType::UPLURAL_TYPE_ORDINAL)
.expect("locale sr_RS exists");
assert_eq!("other", pl.select(0 as f64)?);
assert_eq!("other", pl.select(1 as f64)?);
assert_eq!("other", pl.select(2 as f64)?);
assert_eq!("other", pl.select(6 as f64)?);
assert_eq!("other", pl.select(18 as f64)?);
Ok(())
}
#[test]
fn all_keywords() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new("sr_RS").expect("locale sr_RS exists");
let e = pl.get_keywords()?;
let all: Vec<String> = e.into_iter().map(|r| r.unwrap()).collect();
assert_eq!(vec!["few", "one", "other"], all);
Ok(())
}
#[test]
fn all_keywords_styled() -> Result<(), common::Error> {
let pl = crate::UPluralRules::try_new_styled("sr_RS", UPluralType::UPLURAL_TYPE_ORDINAL)
.expect("locale sr_RS exists");
let e = pl.get_keywords()?;
let all: Vec<String> = e.into_iter().map(|r| r.unwrap()).collect();
assert_eq!(vec!["other"], all);
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_unum/src/lib.rs | rust_icu_unum/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU number formatting support for rust
//!
//! Since 0.3.1
use {
paste, rust_icu_common as common,
rust_icu_common::format_ustring_for_type,
rust_icu_common::generalized_fallible_getter,
rust_icu_common::generalized_fallible_setter,
rust_icu_common::simple_drop_impl,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_uformattable as uformattable, rust_icu_uloc as uloc, rust_icu_ustring as ustring,
rust_icu_ustring::buffered_uchar_method_with_retry,
std::{convert::TryFrom, convert::TryInto, ptr},
};
/// Generates a getter and setter method for a simple attribute with a value
/// of the specified type.
///
/// ```rust ignore
/// impl _ {
/// attribute!(attribute, Attribute, i32, get_prefix, set_prefix)
/// }
/// ```
///
/// generates:
///
/// ```rust ignore
/// impl _ {
/// get_attribute(&self, key: Attribute) -> i32;
/// set_attribute(&self, key: Attribute, value: i32);
/// }
/// ```
///
/// out of functions:
///
/// ```c++ ignore
/// unum_getAttribute(const UNumberFormat* fmt, UNumberFormatAttribute attr);
/// unum_setAttribute(
/// const UNumberFormat* fmt,
/// UNumberFormatAttribute attr,
/// double newValue);
/// ```
macro_rules! attribute{
($method_name:ident, $original_method_name:ident, $type_name:ty) => (
paste::item! {
#[doc = concat!("Implements `", stringify!($original_method_name), "`. Since 0.3.1.")]
pub fn [< get_ $method_name >](&self, attr: sys::UNumberFormatAttribute) -> $type_name {
unsafe {
versioned_function!([< unum_get $original_method_name >])(self.rep.as_ptr(), attr)
}
}
#[doc = concat!("Implements `", stringify!($original_method_name), "`. Since 0.3.1.")]
pub fn [< set_ $method_name >](&mut self, attr: sys::UNumberFormatAttribute, value: $type_name) {
unsafe {
versioned_function!([< unum_set $original_method_name >])(self.rep.as_ptr(), attr, value)
}
}
}
)
}
/// The struct for number formatting.
#[derive(Debug)]
pub struct UNumberFormat {
rep: ptr::NonNull<sys::UNumberFormat>,
}
simple_drop_impl!(UNumberFormat, unum_close);
impl UNumberFormat {
/// Implements `unum_open`, with a pattern. Since 0.3.1.
pub fn try_new_decimal_pattern_ustring(
pattern: &ustring::UChar,
locale: &uloc::ULoc,
) -> Result<UNumberFormat, common::Error> {
UNumberFormat::try_new_style_pattern_ustring(
sys::UNumberFormatStyle::UNUM_PATTERN_DECIMAL,
pattern,
locale,
)
}
/// Implements `unum_open`, with rule-based formatting. Since 0.3.1
pub fn try_new_decimal_rule_based_ustring(
rule: &ustring::UChar,
locale: &uloc::ULoc,
) -> Result<UNumberFormat, common::Error> {
UNumberFormat::try_new_style_pattern_ustring(
sys::UNumberFormatStyle::UNUM_PATTERN_RULEBASED,
rule,
locale,
)
}
/// Implements `unum_open`, with style-based formatting. Since 0.3.1.
pub fn try_new_with_style(
style: sys::UNumberFormatStyle,
locale: &uloc::ULoc,
) -> Result<UNumberFormat, common::Error> {
let rule = ustring::UChar::try_from("")?;
assert_ne!(style, sys::UNumberFormatStyle::UNUM_PATTERN_RULEBASED);
assert_ne!(style, sys::UNumberFormatStyle::UNUM_PATTERN_DECIMAL);
UNumberFormat::try_new_style_pattern_ustring(style, &rule, locale)
}
/// Implements `unum_open`. Since 0.3.1
fn try_new_style_pattern_ustring(
style: sys::UNumberFormatStyle,
pattern: &ustring::UChar,
locale: &uloc::ULoc,
) -> Result<UNumberFormat, common::Error> {
let mut status = common::Error::OK_CODE;
let mut parse = common::NO_PARSE_ERROR.clone();
let loc = locale.as_c_str();
// Unsafety note: all variables should be valid.
let rep = unsafe {
assert!(common::Error::is_ok(status));
assert!(common::parse_ok(parse).is_ok());
versioned_function!(unum_open)(
style,
pattern.as_c_ptr(),
// Mostly OK...
pattern.len() as i32,
loc.as_ptr(),
&mut parse,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
common::parse_ok(parse)?;
assert_ne!(rep, 0 as *mut sys::UNumberFormat);
Ok(UNumberFormat {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Implements `unum_clone`. Since 0.3.1.
pub fn try_clone(&self) -> Result<UNumberFormat, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unum_clone)(self.rep.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(UNumberFormat {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
// Can we make this into a generic method somehow?
// Implements `unum_format`. Since 0.3.1
format_ustring_for_type!(format, unum_format, i32);
// Implements `unum_formatInt64`. Since 0.3.1
format_ustring_for_type!(format_i64, unum_formatInt64, i64);
// Implements `unum_formatDouble`. Since 0.3.1
format_ustring_for_type!(format_f64, unum_formatDouble, f64);
/// Implements `unum_formatDoubleForFields`. Since 0.3.1.
///
/// Returns a formatted Unicode string, with a field position iterator yielding the ranges of
/// each individual formatted field as indexes into the returned string. An UTF8 version of
/// this is not provided because the field position iterator does not give UTF8 compatible
/// character indices.
pub fn format_double_for_fields_ustring<'a>(
&'a self,
number: f64,
) -> Result<
(
ustring::UChar,
UFieldPositionIterator<'a, *const sys::UNumberFormat>,
),
common::Error,
> {
let mut iterator = UFieldPositionIterator::try_new_unowned()?;
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
format_for_fields_impl,
CAPACITY,
[format: *const sys::UNumberFormat, number: f64,],
[iter: *mut sys::UFieldPositionIterator,]
);
let result = format_for_fields_impl(
versioned_function!(unum_formatDoubleForFields),
self.rep.as_ptr(),
number,
iterator.as_mut_ptr(),
)?;
Ok((result, iterator))
}
/// Implements `unum_formatDecimal`. Since 0.3.1.
pub fn format_decimal(&self, decimal: &str) -> Result<String, common::Error> {
let result = self.format_decimal_ustring(decimal)?;
String::try_from(&result)
}
/// Implements `unum_formatDecimal`. Since 0.3.1.
pub fn format_decimal_ustring(&self, decimal: &str) -> Result<ustring::UChar, common::Error> {
use std::os::raw;
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
format_decimal_impl,
CAPACITY,
[
format: *const sys::UNumberFormat,
ptr: *const raw::c_char,
len: i32,
],
[pos: *mut sys::UFieldPosition,]
);
format_decimal_impl(
versioned_function!(unum_formatDecimal),
self.rep.as_ptr(),
decimal.as_ptr() as *const raw::c_char,
decimal.len() as i32,
0 as *mut sys::UFieldPosition,
)
}
/// Implements `unum_formatDoubleCurrency`. Since 0.3.1.
pub fn format_double_currency(
&self,
number: f64,
currency: &str,
) -> Result<String, common::Error> {
let currency = ustring::UChar::try_from(currency)?;
let result = self.format_double_currency_ustring(number, ¤cy)?;
String::try_from(&result)
}
/// Implements `unum_formatDoubleCurrency`. Since 0.3.1
pub fn format_double_currency_ustring(
&self,
number: f64,
currency: &ustring::UChar,
) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
format_double_currency_impl,
CAPACITY,
[
format: *const sys::UNumberFormat,
number: f64,
// NUL terminated!
currency: *mut sys::UChar,
],
[pos: *mut sys::UFieldPosition,]
);
// This piece of gymnastics is required because the currency string is
// expected to be a NUL-terminated UChar. What?!
let mut currencyz = currency.clone();
currencyz.make_z();
format_double_currency_impl(
versioned_function!(unum_formatDoubleCurrency),
self.rep.as_ptr(),
number,
currencyz.as_mut_c_ptr(),
0 as *mut sys::UFieldPosition,
)
}
/// Implements `unum_parseToUFormattable`. Since 0.3.1.
///
/// > **WARNING** the `parse_position` parameter is with respect to the number index
/// in the `UChar` string. This won't work exactly for multibyte UTF8 values of
/// `text`. If you think you will have multibyte values, use instead
/// [UNumberFormat::parse_to_formattable_ustring].
pub fn parse_to_formattable<'a>(
&'a self,
text: &str,
parse_position: Option<i32>,
) -> Result<uformattable::UFormattable<'a>, common::Error> {
let ustr = ustring::UChar::try_from(text)?;
self.parse_to_formattable_ustring(&ustr, parse_position)
}
/// Implements `unum_parseToUFormattable`. Since 0.3.1.
pub fn parse_to_formattable_ustring<'a>(
&'a self,
text: &ustring::UChar,
parse_position: Option<i32>,
) -> Result<uformattable::UFormattable<'a>, common::Error> {
let mut fmt = uformattable::UFormattable::try_new()?;
let mut status = common::Error::OK_CODE;
let mut pos = parse_position.unwrap_or(0);
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unum_parseToUFormattable)(
self.rep.as_ptr(),
fmt.as_mut_ptr(),
text.as_c_ptr(),
text.len() as i32,
&mut pos,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(fmt)
}
/// Implements `unum_formatUFormattable`. Since 0.3.1.
pub fn format_formattable<'a>(
&self,
fmt: &uformattable::UFormattable<'a>,
) -> Result<String, common::Error> {
let result = self.format_formattable_ustring(fmt)?;
String::try_from(&result)
}
/// Implements `unum_formatUFormattable`. Since 0.3.1.
pub fn format_formattable_ustring<'a>(
&self,
fmt: &uformattable::UFormattable<'a>,
) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
format_formattable_impl,
CAPACITY,
[
format: *const sys::UNumberFormat,
fmt: *const sys::UFormattable,
],
[pos: *mut sys::UFieldPosition,]
);
format_formattable_impl(
versioned_function!(unum_formatUFormattable),
self.rep.as_ptr(),
fmt.as_ptr(),
0 as *mut sys::UFieldPosition,
)
}
// Implements `unum_getAttribute`. Since 0.3.1.
attribute!(attribute, Attribute, i32);
// Implements `unum_getDoubleAttribute`. Since 0.3.1.
attribute!(double_attribute, DoubleAttribute, f64);
/// Implements `unum_getTextAttribute`. Since 0.3.1.
pub fn get_text_attribute(
&self,
tag: sys::UNumberFormatTextAttribute,
) -> Result<String, common::Error> {
let result = self.get_text_attribute_ustring(tag)?;
String::try_from(&result)
}
/// Implements `unum_getTextAttribute`. Since 0.3.1.
pub fn get_text_attribute_ustring(
&self,
tag: sys::UNumberFormatTextAttribute,
) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
get_text_attribute_impl,
CAPACITY,
[
rep: *const sys::UNumberFormat,
tag: sys::UNumberFormatTextAttribute,
],
[]
);
get_text_attribute_impl(
versioned_function!(unum_getTextAttribute),
self.rep.as_ptr(),
tag,
)
}
/// Implements `unum_setTextAttribute`. Since 0.3.1.
pub fn set_text_attribute(
&mut self,
tag: sys::UNumberFormatTextAttribute,
new_value: &str,
) -> Result<(), common::Error> {
let new_value = ustring::UChar::try_from(new_value)?;
self.set_text_attribute_ustring(tag, &new_value)?;
Ok(())
}
/// Implements `unum_setTextAttribute`. Since 0.3.1.
pub fn set_text_attribute_ustring(
&mut self,
tag: sys::UNumberFormatTextAttribute,
new_value: &ustring::UChar,
) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unum_setTextAttribute)(
self.rep.as_ptr(),
tag,
new_value.as_c_ptr(),
new_value.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(())
}
/// Implements `unum_toPattern`. Since 0.3.1.
pub fn get_pattern(&self, is_localized: bool) -> Result<String, common::Error> {
let result = self.get_pattern_ustring(is_localized)?;
String::try_from(&result)
}
/// Implements `unum_toPattern`. Since 0.3.1.
pub fn get_pattern_ustring(&self, is_localized: bool) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
get_pattern_ustring_impl,
CAPACITY,
[rep: *const sys::UNumberFormat, is_localized: sys::UBool,],
[]
);
let result = get_pattern_ustring_impl(
versioned_function!(unum_toPattern),
self.rep.as_ptr(),
is_localized as sys::UBool,
);
result
}
/// Implements `unum_getSymbol`. Since 0.3.1.
pub fn get_symbol(&self, symbol: sys::UNumberFormatSymbol) -> Result<String, common::Error> {
let result = self.get_symbol_ustring(symbol)?;
String::try_from(&result)
}
/// Implements `unum_getSymbol`. Since 0.3.1.
pub fn get_symbol_ustring(
&self,
symbol: sys::UNumberFormatSymbol,
) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
get_symbol_impl,
CAPACITY,
[
rep: *const sys::UNumberFormat,
symbol: sys::UNumberFormatSymbol,
],
[]
);
get_symbol_impl(
versioned_function!(unum_getSymbol),
self.rep.as_ptr(),
symbol,
)
}
/// Implements `unum_setSymbol`. Since 0.3.1.
pub fn set_symbol(
&mut self,
symbol: sys::UNumberFormatSymbol,
value: &str,
) -> Result<(), common::Error> {
let value = ustring::UChar::try_from(value)?;
self.set_symbol_ustring(symbol, &value)
}
/// Implements `unum_setSymbol`. Since 0.3.1.
pub fn set_symbol_ustring(
&mut self,
symbol: sys::UNumberFormatSymbol,
value: &ustring::UChar,
) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unum_setSymbol)(
self.rep.as_ptr(),
symbol,
value.as_c_ptr(),
value.len() as i32,
&mut status,
);
};
common::Error::ok_or_warning(status)?;
Ok(())
}
/// Implements `unum_getLocaleByType`. Since 0.3.1.
pub fn get_locale_by_type<'a>(
&'a self,
data_loc_type: sys::ULocDataLocaleType,
) -> Result<&'a str, common::Error> {
let mut status = common::Error::OK_CODE;
let cptr = unsafe {
assert!(common::Error::is_ok(status));
let raw = versioned_function!(unum_getLocaleByType)(
self.rep.as_ptr(),
data_loc_type,
&mut status,
);
std::ffi::CStr::from_ptr(raw)
};
common::Error::ok_or_warning(status)?;
cptr.to_str().map_err(|e| e.into())
}
// Implements `unum_getContext`. Since 0.3.1.
generalized_fallible_getter!(
get_context,
unum_getContext,
[context_type: sys::UDisplayContextType,],
sys::UDisplayContext
);
// Implements `unum_setContext`. Since 0.3.1.
generalized_fallible_setter!(set_context, unum_setContext, [value: sys::UDisplayContext,]);
}
/// Used to iterate over the field positions.
pub struct UFieldPositionIterator<'a, T> {
rep: ptr::NonNull<sys::UFieldPositionIterator>,
// Owner does not own the representation above, but does own the underlying
// data. That's why we let the owner squat here to ensure proper lifetime
// containment.
#[allow(dead_code)]
owner: Option<&'a T>,
}
impl<'a, T> Drop for UFieldPositionIterator<'a, T> {
fn drop(&mut self) {
unsafe { versioned_function!(ufieldpositer_close)(self.rep.as_ptr()) };
}
}
impl<'a, T: 'a> UFieldPositionIterator<'a, T> {
/// Try creating a new iterator, based on data supplied by `owner`.
pub fn try_new_owned(owner: &'a T) -> Result<UFieldPositionIterator<'a, T>, common::Error> {
let raw = Self::new_raw()?;
Ok(UFieldPositionIterator {
rep: ptr::NonNull::new(raw).expect("raw pointer is not null"),
owner: Some(owner),
})
}
/// Try creating a new iterator, based on data with independent lifetime.
pub fn try_new_unowned<'b>() -> Result<UFieldPositionIterator<'b, T>, common::Error> {
let raw = Self::new_raw()?;
Ok(UFieldPositionIterator {
rep: ptr::NonNull::new(raw).expect("raw pointer is not null"),
owner: None,
})
}
fn new_raw() -> Result<*mut sys::UFieldPositionIterator, common::Error> {
let mut status = common::Error::OK_CODE;
let raw = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ufieldpositer_open)(&mut status)
};
common::Error::ok_or_warning(status)?;
assert_ne!(raw, 0 as *mut sys::UFieldPositionIterator);
Ok(raw)
}
/// Returns the interal representation pointer.
///
/// **DO NOT USE UNLESS IMPLEMENTING LOW-LEVEL ICU4C INTERFACE**.
#[doc(hidden)]
pub fn as_mut_ptr(&mut self) -> *mut sys::UFieldPositionIterator {
self.rep.as_ptr()
}
}
/// Returned by [UFieldPositionIterator], represents the spans of each type of
/// the formatting string.
#[derive(Debug, PartialEq)]
pub struct UFieldPositionType {
/// The field type for the formatting.
pub field_type: i32,
/// The index in the buffer at which the range of interest begins. For
/// example, in a string "42 RSD", the beginning of "42" would be at index 0.
pub begin_index: i32,
/// The index one past the end of the buffer at which the range of interest ends.
/// For example, in a string "42 RSD", the end of "42" would be at index 2.
pub past_end_index: i32,
}
impl<'a, T> Iterator for UFieldPositionIterator<'a, T> {
// TODO: Consider turning this into a range once the range properties
// are known.
/// The begin of the range and the end of the range index, in that order.
type Item = UFieldPositionType;
/// Gets the next position iterator pair.
fn next(&mut self) -> Option<Self::Item> {
let mut begin = 0i32;
let mut end = 0i32;
let field_type = unsafe {
versioned_function!(ufieldpositer_next)(self.rep.as_ptr(), &mut begin, &mut end)
};
if field_type < 0 {
return None;
}
Some(UFieldPositionType {
field_type,
begin_index: begin,
past_end_index: end,
})
}
}
/// Gets an iterator over all available formatting locales.
///
/// Implements `unum_getAvailable`. Since 0.3.1.
pub fn available_iter() -> UnumIter {
let max = get_num_available();
UnumIter { max, next: 0 }
}
fn get_num_available() -> usize {
let result = unsafe { versioned_function!(unum_countAvailable)() } as usize;
result
}
/// An iterator returned by `available_iter()`, containing the string representation of locales for
/// which formatting is available.
pub struct UnumIter {
/// The total number of elements that this iterator can yield.
max: usize,
/// The next element index that can be yielded.
next: usize,
}
impl Iterator for UnumIter {
type Item = String;
/// Yields the next available locale identifier per the currently loaded locale data.
///
/// Example values: `en_US`, `rs`, `ru_RU`.
fn next(&mut self) -> Option<String> {
if self.max == 0 {
return None;
}
if self.max != get_num_available() {
// If the number of available locales changed while we were iterating this list, the
// locale set may have been reloaded. Return early to avoid indexing beyond limits.
// This may return weird results, but won't crash the program.
return None;
}
if self.next >= self.max {
return None;
}
let cptr: *const std::os::raw::c_char =
unsafe { versioned_function!(unum_getAvailable)(self.next as i32) };
// This assertion could happen in theory if the locale data is invalidated as this iterator
// is being executed. I am unsure how that can be prevented.
assert_ne!(
cptr,
std::ptr::null(),
"unum_getAvailable unexpectedly returned nullptr"
);
let cstr = unsafe { std::ffi::CStr::from_ptr(cptr) };
self.next = self.next + 1;
Some(cstr.to_str().expect("can be converted to str").to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_decimal_pattern_ustring() {
struct TestCase {
locale: &'static str,
number: i32,
pattern: &'static str,
expected: &'static str,
}
let tests = vec![TestCase {
locale: "sr-RS",
number: 42,
pattern: "",
expected: "42",
}];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let pattern = ustring::UChar::try_from(test.pattern).expect("pattern is set");
let fmt = crate::UNumberFormat::try_new_decimal_pattern_ustring(&pattern, &locale)
.expect("formatter");
let result = fmt
.try_clone()
.expect("clone")
.format(test.number)
.expect("format success");
assert_eq!(test.expected, result);
}
}
// TODO: find example rules.
#[test]
#[should_panic(expected = "U_MEMORY_ALLOCATION_ERROR")]
fn format_decimal_rulebased_ustring() {
struct TestCase {
locale: &'static str,
number: i32,
rule: &'static str,
expected: &'static str,
}
let tests = vec![TestCase {
locale: "sr-RS",
number: 42,
rule: "",
expected: "42",
}];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let pattern = ustring::UChar::try_from(test.rule).expect("pattern is set");
let fmt = crate::UNumberFormat::try_new_decimal_rule_based_ustring(&pattern, &locale)
.expect("formatter");
let result = fmt
.try_clone()
.expect("clone")
.format(test.number)
.expect("format success");
assert_eq!(test.expected, result);
}
}
// TODO: add more, and relevant test cases.
#[test]
fn format_style_ustring() {
struct TestCase {
locale: &'static str,
number: i32,
style: sys::UNumberFormatStyle,
expected: &'static str,
}
let tests = vec![
TestCase {
locale: "sr-RS",
number: 42,
style: sys::UNumberFormatStyle::UNUM_CURRENCY,
expected: "42\u{a0}RSD",
},
TestCase {
locale: "sr-RS",
number: 42,
style: sys::UNumberFormatStyle::UNUM_SPELLOUT,
expected: "четрдесет и два",
},
];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let fmt =
crate::UNumberFormat::try_new_with_style(test.style, &locale).expect("formatter");
let result = fmt
.try_clone()
.expect("clone")
.format(test.number)
.expect("format success");
assert_eq!(test.expected, result);
}
}
#[test]
fn format_double_with_fields() {
struct TestCase {
locale: &'static str,
number: f64,
style: sys::UNumberFormatStyle,
expected: &'static str,
expected_iter: Vec<UFieldPositionType>,
}
let tests = vec![TestCase {
locale: "sr-RS",
number: 42.1,
style: sys::UNumberFormatStyle::UNUM_CURRENCY,
expected: "42\u{a0}RSD",
expected_iter: vec![
// "42"
UFieldPositionType {
field_type: 0,
begin_index: 0,
past_end_index: 2,
},
// "RSD"
UFieldPositionType {
field_type: 7,
begin_index: 3,
past_end_index: 6,
},
],
}];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let fmt =
crate::UNumberFormat::try_new_with_style(test.style, &locale).expect("formatter");
let (ustring, iter) = fmt
.format_double_for_fields_ustring(test.number)
.expect("format success");
let s = String::try_from(&ustring)
.expect(&format!("string is convertible to utf8: {:?}", &ustring));
assert_eq!(test.expected, s);
let iter_values = iter.collect::<Vec<UFieldPositionType>>();
assert_eq!(test.expected_iter, iter_values);
}
}
#[test]
fn format_decimal() {
struct TestCase {
locale: &'static str,
number: &'static str,
style: sys::UNumberFormatStyle,
expected: &'static str,
}
let tests = vec![TestCase {
locale: "sr-RS",
number: "1300.55",
style: sys::UNumberFormatStyle::UNUM_CURRENCY,
expected: "1.301\u{a0}RSD",
}];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let fmt =
crate::UNumberFormat::try_new_with_style(test.style, &locale).expect("formatter");
let s = fmt.format_decimal(test.number).expect("format success");
assert_eq!(test.expected, s);
}
}
#[test]
fn format_double_currency() {
struct TestCase {
locale: &'static str,
number: f64,
currency: &'static str,
style: sys::UNumberFormatStyle,
expected: &'static str,
}
let tests = vec![TestCase {
locale: "sr-RS",
number: 1300.55,
currency: "usd",
style: sys::UNumberFormatStyle::UNUM_CURRENCY,
expected: "1.300,55\u{a0}US$",
}];
for test in tests {
let locale = uloc::ULoc::try_from(test.locale).expect("locale exists");
let fmt =
crate::UNumberFormat::try_new_with_style(test.style, &locale).expect("formatter");
let s = fmt
.format_double_currency(test.number, test.currency)
.expect("format success");
assert_eq!(test.expected, s);
}
}
#[test]
fn format_and_parse_uformattable() {
#[derive(Debug)]
struct TestCase {
source_locale: &'static str,
number: &'static str,
position: Option<i32>,
style: sys::UNumberFormatStyle,
target_locale: &'static str,
expected: &'static str,
}
let tests = vec![
TestCase {
source_locale: "sr-RS",
number: "123,44",
position: None,
style: sys::UNumberFormatStyle::UNUM_DECIMAL,
target_locale: "en-US",
expected: "123.44",
},
TestCase {
source_locale: "sr-RS",
number: "123,44",
position: Some(2),
style: sys::UNumberFormatStyle::UNUM_DECIMAL,
target_locale: "en-US",
expected: "3.44",
},
];
for test in tests {
let locale = uloc::ULoc::try_from(test.source_locale).expect("locale exists");
let fmt = crate::UNumberFormat::try_new_with_style(test.style, &locale)
.expect("source_locale formatter");
let formattable = fmt
.parse_to_formattable(test.number, test.position)
.expect(&format!("parse_to_formattable: {:?}", &test));
let locale = uloc::ULoc::try_from(test.target_locale).expect("locale exists");
let fmt = crate::UNumberFormat::try_new_with_style(test.style, &locale)
.expect("target_locale formatter");
let result = fmt
.format_formattable(&formattable)
.expect(&format!("format_formattable: {:?}", &test));
assert_eq!(test.expected, result);
}
}
#[test]
fn test_available() {
// Since the locale list is variable, we can not test for exact locales, but
// we count them and make a sample to ensure sanity.
let all = super::available_iter().collect::<Vec<String>>();
let count = super::available_iter().count();
assert_ne!(
0, count,
"there should be at least some available locales: {:?}",
&all
);
let available = all
.into_iter()
.filter(|f| *f == "en_US")
.collect::<Vec<String>>();
assert_eq!(
vec!["en_US"],
available,
"missing a locale that likely should be there"
);
}
#[test]
fn pattern() {
#[derive(Debug)]
struct TestCase {
source_locale: &'static str,
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_udata/src/lib.rs | rust_icu_udata/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::path::Path;
use std::ffi;
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
std::convert::TryFrom, std::os::raw,
};
/// Variants of [UDataMemory].
#[derive(Debug)]
enum Rep {
/// The data memory is backed by a user-supplied buffer.
Buffer(Vec<u8>),
/// The data memory is backed by a resource file.
Resource(
// This would have been std::ptr::NonNull if we didn't have to
// implement Send and Sync.
// We only ever touch this pointer in Rust when we initialize
// Rep::Resource, and when we dealocate Rep::Resource.
*const sys::UDataMemory,
),
}
// Safety: The *const sys::UDataMemory above is only used by the underlying C++
// library.
unsafe impl Send for Rep {}
unsafe impl Sync for Rep {}
/// Sets the directory from which to load ICU data resources.
///
/// Implements `u_setDataDirectory`.
pub fn set_data_directory(dir: &Path) {
let dir_cstr = ffi::CString::new
(dir.to_str().expect("this should never be a runtime error"))
.expect("this should never be a runtim error");
unsafe {
versioned_function!(u_setDataDirectory)(dir_cstr.as_ptr())
};
}
/// The type of the ICU resource requested. Some standard resources have their
/// canned types. In case you run into one that is not captured here, use `Custom`,
/// and consider sending a pull request to add the new resource type.
pub enum Type {
/// An empty resource type. This is ostensibly allowed, but unclear when
/// it is applicable.
Empty,
/// The unpacked resource type, equivalent to "res" in ICU4C.
Res,
/// The cnv resource type, equivalent to "cnv" in ICU4C.
Cnv,
/// The "common" data type, equivalent to "dat" in ICU4C.
Dat,
/// A custom data type, in case none of the above fit your use case. It
/// is not clear whether this would ever be useful, but the ICU4C API
/// allows for it, so we must too.
Custom(String),
}
impl AsRef<str> for Type {
fn as_ref(&self) -> &str {
match self {
Type::Empty => &"",
Type::Res => &"res",
Type::Dat => &"dat",
Type::Cnv => &"cnv",
Type::Custom(ref s) => &s,
}
}
}
/// Implements `UDataMemory`.
///
/// Represents data memory backed by a borrowed memory buffer used for loading ICU data.
/// [UDataMemory] is very much not thread safe, as it affects the global state of the ICU library.
/// This suggests that the best way to use this data is to load it up in a main thread, or access
/// it through a synchronized wrapper.
#[derive(Debug)]
pub struct UDataMemory {
// The internal representation of [UDataMemory].
// May vary, depending on the way the struct is created.
//
// See: [UDataMemory::try_from] and [UDataMemory::open].
rep: Rep,
}
impl Drop for UDataMemory {
// Implements `u_cleanup`.
fn drop(&mut self) {
if let Rep::Resource(r) = self.rep {
unsafe {
// Safety: there is no other way to close the memory that the
// underlying C++ library uses but to pass it into this function.
versioned_function!(udata_close)(r as *mut sys::UDataMemory)
};
}
// Without this, resource references will remain, but memory will be gone.
unsafe {
// Safety: no other way to call this function.
versioned_function!(u_cleanup)()
};
}
}
impl TryFrom<Vec<u8>> for crate::UDataMemory {
type Error = common::Error;
/// Makes a UDataMemory out of a buffer.
///
/// Implements `udata_setCommonData`.
fn try_from(buf: Vec<u8>) -> Result<Self, Self::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
// Expects that buf is a valid pointer and that it contains valid
// ICU data. If data is invalid, an error status will be set.
// No guarantees for invalid pointers.
unsafe {
versioned_function!(udata_setCommonData)(
buf.as_ptr() as *const raw::c_void,
&mut status,
);
};
common::Error::ok_or_warning(status)?;
Ok(UDataMemory { rep: Rep::Buffer(buf) })
}
}
impl crate::UDataMemory {
/// Uses the resources from the supplied resource file.
///
/// This may end up being more efficient compared to loading from a buffer,
/// as ostensibly the resources would be memory mapped to only the needed
/// parts.
///
/// - The `path` is the file path at which to find the resource file. Ostensibly
/// specifying `None` here will load from the "default" ICU_DATA path.
/// I have not been able to confirm this.
///
/// - The `a_type` is the type of the resource file. It is not clear whether
/// the resource file type is a closed or open set, so we provide for both
/// possibilities.
///
/// - The `name` is the name of the resource file. It is documented nullable
/// in the ICU documentation. Pass `None` here to pass nullptr to the
/// underlying C API.
///
/// Presumably using `UDataMemory::open(Some("/dir/too"), Type::Res, Some("filename")` would
/// attempt to load ICU data from `/dir/too/filename.res`, as well as some other
/// canonical permutations of the above. The full documentation is
/// [here][1], although I could not confirm that the documentation is actually
/// describing what the code does. Also, using `None` at appropriate places
/// seems to be intended to load data from [some "default" sites][2]. I have
/// however observed that the actual behavior diverges from that documentation.
///
/// Implements `udata_open`.
///
/// [1]: https://unicode-org.github.io/icu/userguide/icu_data/#how-data-loading-works
/// [2]: https://unicode-org.github.io/icu/userguide/icu_data/#icu-data-directory
pub fn open(path: Option<&Path>, a_type: Type, name: Option<&str>) -> Result<Self, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let path_cstr = path.map(|s| { ffi::CString::new(s.to_str().expect("should never be a runtime error")).unwrap()});
let name_cstr = name.map(|s| { ffi::CString::new(s).expect("should never be a runtime error") } );
let type_cstr = ffi::CString::new(a_type.as_ref()).expect("should never be a runtime errror");
let rep = Self::get_resource(
path_cstr.as_ref().map(|s| s.as_c_str()),
type_cstr.as_c_str(),
name_cstr.as_ref().map(|s| s.as_c_str()),
&mut status);
common::Error::ok_or_warning(status)?;
// Make sure that all CStrs outlive the call to Self::get_resource. It is
// all too easy to omit `path_cstr.as_ref()` above, resulting in *_cstr
// being destroyed before a call to Self::get_resource happens. Fun.
let (_a, _b, _c) = (path_cstr, name_cstr, type_cstr);
Ok(crate::UDataMemory{ rep })
}
fn get_resource(path: Option<&ffi::CStr>, a_type: &ffi::CStr, name: Option<&ffi::CStr>, status: &mut sys::UErrorCode) -> Rep {
unsafe {
// Safety: we do what we must to call the underlying unsafe C API, and only return an
// opaque enum, to ensure that no rust client code may touch the raw pointer.
assert!(common::Error::is_ok(*status));
// Would be nicer if there were examples of udata_open usage to
// verify this.
let rep: *const sys::UDataMemory = versioned_function!(udata_open)(
path.map(|s| s.as_ptr()).unwrap_or(std::ptr::null()),
a_type.as_ptr(),
name.map(|c| c.as_ptr()).unwrap_or(std::ptr::null()),
status);
// Sadly we can not use NonNull, as we can not make the resulting
// type Sync or Send.
assert!(!rep.is_null());
Rep::Resource(rep)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Mutex, Weak, Arc};
use std::thread;
// We don't use UDataMemory in threaded contexts, but our users do. So let's
// ensure we can do this.
#[test]
fn send_sync_impl() {
let memory: Arc<Mutex<Weak<UDataMemory>>>= Arc::new(Mutex::new(Weak::new()));
// Ensure Sync.
let _clone = memory.clone();
thread::spawn(move || {
// Ensure Send.
let _m = memory;
});
}
#[test]
fn send_impl() {
let memory: Weak<UDataMemory> = Weak::new();
let _clone = memory.clone();
thread::spawn(move || {
let _m = memory;
});
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ucnv/src/lib.rs | rust_icu_ucnv/src/lib.rs | // Copyright 2021 Luis Cáceres
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU character conversion support for rust
//!
//! This crate provides [character encoding translation](https://en.wikipedia.org/wiki/Character_encoding#Character_encoding_translation),
//! based on the conversion functions implemented by the ICU library.
//! Specifically the functionality exposed through its C API, as available in the [header
//! `ucnv.h`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ucnv_8h.html).
//!
//! The main type is [UConverter], which can be created using `UConverter::open` with an encoding
//! name (as a `&str`). This type provides conversion functions between UTF-16 and the
//! provided encoding.
//!
//! This crate also provides [utf8::Converter] as a convenience type to work directly with UTF-8
//! strings, such as with Rust's `&str` and `String` types.
//!
//! For more information on ICU conversion, an interested reader can check out the
//! [conversion documentation on the ICU user guide](https://unicode-org.github.io/icu/userguide/conversion/).
//!
//! > Are you missing some features from this crate? Consider [reporting an
//! issue](https://github.com/google/rust_icu/issues) or even [contributing the
//! functionality](https://github.com/google/rust_icu/pulls).
use std::{
ffi::{CStr, CString},
ops::Range,
os::raw,
ptr::{null_mut, NonNull},
};
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
};
pub mod utf8;
/// Get an iterator over all canonical converter names available to ICU.
///
/// The [AvailableConverters] iterator efficiently implements [Iterator::count] and [Iterator::nth]
/// to avoid calling `ucnv_getAvailableName` unnecessarily.
///
/// This interface wraps around `ucnv_countAvailable` and `ucnv_getAvailableName`.
pub fn available_converters() -> AvailableConverters {
AvailableConverters {
n: 0,
count: unsafe { versioned_function!(ucnv_countAvailable)() } as u32,
}
}
/// See [available_converters()]
pub struct AvailableConverters {
n: u32,
count: u32,
}
impl AvailableConverters {
#[inline(always)]
fn elements_left(&self) -> usize {
self.count.saturating_sub(self.n) as usize
}
}
impl Iterator for AvailableConverters {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let name_c_str = unsafe { versioned_function!(ucnv_getAvailableName)(self.n as i32) };
if name_c_str.is_null() {
return None;
}
self.n += 1;
unsafe {
Some(
CStr::from_ptr(name_c_str)
.to_str()
.expect("converter name should be UTF-8 compatible")
.to_string(),
)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let count = self.elements_left();
(count, Some(count))
}
fn count(self) -> usize {
self.elements_left()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
if n >= self.elements_left() {
self.n = self.count;
None
} else {
self.n += n as u32;
self.next()
}
}
}
impl ExactSizeIterator for AvailableConverters {}
/// Get an iterator over all aliases for the provided converter name (which may not necessarily be
/// the canonical converter name).
///
/// The [Aliases] iterator efficiently implements [Iterator::count] and [Iterator::nth] to avoid
/// calling `ucnv_getAlias` unnecessarily.
///
/// This interface wraps around `ucnv_countAliases` and `ucnv_getAlias`.
pub fn aliases(name: &str) -> Aliases {
let name = CString::new(name).expect("converter name should not contain NUL");
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let count = unsafe { versioned_function!(ucnv_countAliases)(name.as_ptr(), &mut status) };
let is_ambiguous = status == sys::UErrorCode::U_AMBIGUOUS_ALIAS_WARNING;
Aliases {
n: 0,
count,
name,
is_ambiguous,
}
}
/// See [aliases()]
pub struct Aliases {
n: u16,
count: u16,
name: CString,
is_ambiguous: bool,
}
impl Aliases {
#[inline(always)]
fn elements_left(&self) -> usize {
self.count.saturating_sub(self.n) as usize
}
/// Whether or not the converter name provided to [aliases()] is an ambiguous name.
///
/// This value is the cached result of checking that the `status` of calling `ucnv_countAliases`
/// was set to `U_AMBIGUOUS_ALIAS_WARNING`.
pub fn is_ambiguous(&self) -> bool {
self.is_ambiguous
}
}
impl Iterator for Aliases {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let alias_c_str = unsafe {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
versioned_function!(ucnv_getAlias)(self.name.as_ptr(), self.n, &mut status)
};
if alias_c_str.is_null() {
return None;
}
self.n += 1;
unsafe {
Some(
CStr::from_ptr(alias_c_str)
.to_str()
.expect("alias name should be UTF-8 compatible")
.to_string(),
)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let count = self.elements_left();
(count, Some(count))
}
fn count(self) -> usize {
self.elements_left()
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
if n >= self.elements_left() {
self.n = self.count;
None
} else {
self.n += n as u16;
self.next()
}
}
}
impl ExactSizeIterator for Aliases {}
/// The result of a feed/stream operation on a converter.
///
/// See [UConverter] for examples.
pub struct FeedResult {
/// Indicates how many units have been written to the destination buffer.
pub dst_consumed: usize,
/// Indicates how many units of the source buffer have been read and processed by the converter.
pub src_consumed: usize,
/// The status error reported by the underlying ICU call.
pub result: Result<(), common::Error>,
}
/// The converter type that provides conversion to/from UTF-16.
///
/// This object can perform conversion of single strings (using the
/// [UConverter::convert_to_uchars] and [UConverter::convert_from_uchars] functions) or of a stream
/// of text data (using the [UConverter::feed_to_uchars] and [UConverter::feed_from_uchars] functions
/// to feed and process more input data).
///
/// Each conversion direction has separate state, which means you can use the `feed_to_uchars`
/// function at the same time as the `feed_from_uchars` to process two streams simultaneously *in
/// the same thread* (note that this type isn't [Sync]).
///
///
/// ## Examples
///
/// ### Single-string conversion
///
/// The single-string conversion functions are straightforward to use.
///
/// ```
/// # use rust_icu_ucnv::UConverter;
/// #
/// let mut converter = UConverter::open("UTF-8").unwrap();
///
/// let utf8_string = "スーパー";
/// let utf16_string: Vec<u16> = converter.convert_to_uchars(utf8_string.as_bytes()).unwrap();
///
/// assert_eq!(
/// utf8_string,
/// std::str::from_utf8(&converter.convert_from_uchars(&utf16_string).unwrap()).unwrap()
/// );
/// ```
///
/// ### Streaming conversion
///
/// The feeding/streaming functions take a mutable slice as destination buffer and an immutable
/// slice as source buffer. These functions consume the source buffer and write the converted text
/// into the destination buffer until one or the other have been fully consumed, or some conversion
/// error happens. These functions return the error (if any) and how much of the destination/source
/// buffers has been consumed. The idea is that after one of the buffer has been fully consumed, you
/// grab another buffer chunk (whether source or destination) and call the function again. Hence,
/// a processing loop might look like this:
///
/// ```
/// # use rust_icu_ucnv::UConverter;
/// use rust_icu_common as common;
/// use rust_icu_sys as sys;
///
/// # const UTF8_STRING: &str = "Shift_JIS(シフトジス)は、コンピュータ上で日本語を含む文字列を表現するために\
/// # 用いられる文字コードの一つ。シフトJIS(シフトジス)と表記されることもある。";
/// #
/// let mut converter = UConverter::open("UTF-8").unwrap();
///
/// # let mut dst_buffer: Vec<u16> = Vec::new();
/// # dst_buffer.resize(1024, 0);
/// #
/// # let mut dst_chunks = dst_buffer.chunks_mut(8);
/// # let mut get_dst_chunk = move || dst_chunks.next();
/// #
/// # let mut src_chunks = UTF8_STRING.as_bytes().chunks(6);
/// # let mut get_src_chunk = move || src_chunks.next();
/// #
/// let mut dst: &mut [u16] = get_dst_chunk().unwrap();
/// let mut src: &[u8] = get_src_chunk().unwrap();
///
/// // reset any previous state
/// converter.reset_to_uchars();
/// loop {
/// let res = converter.feed_to_uchars(dst, src);
/// match res.result {
/// Ok(_) | Err(common::Error::Sys(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR)) => {
/// dst = dst.split_at_mut(res.dst_consumed).1;
/// src = src.split_at(res.src_consumed).1;
/// }
/// _ => panic!("conversion error"),
/// }
///
/// if dst.is_empty() {
/// dst = get_dst_chunk().unwrap();
/// }
/// if src.is_empty() {
/// src = match get_src_chunk() {
/// None => break,
/// Some(src) => src,
/// };
/// }
/// }
/// ```
#[derive(Debug)]
pub struct UConverter(NonNull<sys::UConverter>);
unsafe impl Send for UConverter {}
impl UConverter {
/// Attempts to open a converter with the given encoding name.
///
/// This function wraps around `ucnv_open`.
pub fn open(name: &str) -> Result<Self, common::Error> {
let name_c_str = CString::new(name).expect("converter name must not contain NUL");
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let converter_ptr =
unsafe { versioned_function!(ucnv_open)(name_c_str.as_ptr(), &mut status) };
common::Error::ok_or_warning(status)?;
Ok(Self(
NonNull::new(converter_ptr).expect("converter pointer should not be null"),
))
}
/// Attempts to clone a given converter.
///
/// This function wraps around `ucnv_safeClone`.
pub fn try_clone(&self) -> Result<Self, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let converter_ptr = unsafe {
versioned_function!(ucnv_safeClone)(
self.0.as_ptr(),
null_mut(),
null_mut(),
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(Self(
NonNull::new(converter_ptr).expect("converter pointer should not be null"),
))
}
/// Determines whether the converter contains ambiguous mappings of the same character.
///
/// This function wraps around `ucnv_isAmbiguous`.
pub fn has_ambiguous_mappings(&self) -> bool {
unsafe { versioned_function!(ucnv_isAmbiguous)(self.0.as_ptr()) != 0 }
}
/// Attempts to get the canonical name of the converter.
///
/// This function wraps around `ucnv_getName`.
pub fn name(&self) -> Result<&str, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let name_c_str = unsafe { versioned_function!(ucnv_getName)(self.0.as_ptr(), &mut status) };
common::Error::ok_or_warning(status)?;
unsafe {
Ok(CStr::from_ptr(name_c_str)
.to_str()
.expect("converter name is UTF-8 compatible"))
}
}
/// Resets the converter to a default state.
///
/// This is equivalent to calling both [UConverter::reset_to_uchars] and [UConverter::reset_from_uchars].
///
/// This function wraps around `ucnv_reset`.
pub fn reset(&mut self) {
unsafe { versioned_function!(ucnv_reset)(self.0.as_ptr()) }
}
/// Resets the `*_to_uchars` part of the converter to a default state.
///
/// It is necessary to call this function when you want to start processing a new data stream
/// using [UConverter::feed_to_uchars].
///
/// This function wraps around `ucnv_resetToUnicode`.
pub fn reset_to_uchars(&mut self) {
unsafe { versioned_function!(ucnv_resetToUnicode)(self.0.as_ptr()) }
}
/// Resets the `*_from_uchars` part of the converter to a default state.
///
/// It is necessary to call this function when you want to start processing a new data stream
/// using [UConverter::feed_from_uchars].
///
/// This function wraps around `ucnv_resetFromUnicode`.
pub fn reset_from_uchars(&mut self) {
unsafe { versioned_function!(ucnv_resetFromUnicode)(self.0.as_ptr()) }
}
/// Feeds more encoded data to be decoded to UTF-16 and put in the provided destination buffer.
///
/// Make sure to call [UConverter::reset_to_uchars] before processing a new data stream.
///
/// This function wraps around `ucnv_toUnicode`.
pub fn feed_to_uchars(&mut self, dst: &mut [sys::UChar], src: &[u8]) -> FeedResult {
self.feed_to(dst, src)
}
/// Feeds more UTF-16 to be encoded and put in the provided destination buffer.
///
/// Make sure to call [UConverter::reset_from_uchars] before processing a new data stream.
///
/// This function wraps around `ucnv_fromUnicode`.
pub fn feed_from_uchars(&mut self, dst: &mut [u8], src: &[sys::UChar]) -> FeedResult {
self.feed_from(dst, src)
}
/// Performs single-string conversion from an encoded string to a UTF-16 string.
///
/// Note that this function resets the `*_to_uchars` state before conversion.
pub fn convert_to_uchars(&mut self, src: &[u8]) -> Result<Vec<sys::UChar>, common::Error> {
self.reset_to_uchars();
self.convert_to(src)
}
/// Performs single-string conversion from a UTF-16 string to an encoded string.
///
/// Note that this function resets the `*_from_uchars` state before conversion.
pub fn convert_from_uchars(&mut self, src: &[sys::UChar]) -> Result<Vec<u8>, common::Error> {
self.reset_from_uchars();
self.convert_from(src)
}
}
impl FeedConverterRaw for UConverter {
type ToUnit = sys::UChar;
type FromUnit = u8;
unsafe fn feed_to_raw(
&mut self,
dst: &mut Range<*mut Self::ToUnit>,
src: &mut Range<*const Self::FromUnit>,
should_flush: bool,
) -> sys::UErrorCode {
// `ucnv_toUnicode` takes a c_char pointer
let mut src_range = Range {
start: src.start as *const raw::c_char,
end: src.end as *const raw::c_char,
};
let mut status = sys::UErrorCode::U_ZERO_ERROR;
versioned_function!(ucnv_toUnicode)(
self.0.as_ptr(),
&mut dst.start,
dst.end,
&mut src_range.start,
src_range.end,
null_mut(),
should_flush.into(),
&mut status,
);
// update actual src range
src.start = src_range.start as *const u8;
return status;
}
unsafe fn feed_from_raw(
&mut self,
dst: &mut Range<*mut Self::FromUnit>,
src: &mut Range<*const Self::ToUnit>,
should_flush: bool,
) -> sys::UErrorCode {
// `ucnv_fromUnicode` takes a c_char pointer
let mut dst_range = Range {
start: dst.start as *mut raw::c_char,
end: dst.end as *mut raw::c_char,
};
let mut status = sys::UErrorCode::U_ZERO_ERROR;
versioned_function!(ucnv_fromUnicode)(
self.0.as_ptr(),
&mut dst_range.start,
dst_range.end,
&mut src.start,
src.end,
null_mut(),
should_flush.into(),
&mut status,
);
// update actual src range
dst.start = dst_range.start as *mut u8;
return status;
}
}
// A private helper trait used to implement single-string conversion (convert_* functions) and
// feeding conversion (feed_* functions) on top of the raw feeding/streaming API exposed by ICU.
trait FeedConverterRaw {
// `dst` type when calling *_to functions
type ToUnit;
// `dst` type when calling *_from functions
type FromUnit;
// These functions essentially wrap the ICU call.
unsafe fn feed_to_raw(
&mut self,
dst: &mut Range<*mut Self::ToUnit>,
src: &mut Range<*const Self::FromUnit>,
should_flush: bool,
) -> sys::UErrorCode;
unsafe fn feed_from_raw(
&mut self,
dst: &mut Range<*mut Self::FromUnit>,
src: &mut Range<*const Self::ToUnit>,
should_flush: bool,
) -> sys::UErrorCode;
#[inline(always)]
fn feed_to(&mut self, dst: &mut [Self::ToUnit], src: &[Self::FromUnit]) -> FeedResult {
let mut dst_range = dst.as_mut_ptr_range();
let mut src_range = src.as_ptr_range();
let status = unsafe { self.feed_to_raw(&mut dst_range, &mut src_range, false) };
FeedResult {
dst_consumed: unsafe { dst_range.start.offset_from(dst.as_mut_ptr()) } as usize,
src_consumed: unsafe { src_range.start.offset_from(src.as_ptr()) } as usize,
result: common::Error::ok_or_warning(status),
}
}
#[inline(always)]
fn feed_from(&mut self, dst: &mut [Self::FromUnit], src: &[Self::ToUnit]) -> FeedResult {
let mut dst_range = dst.as_mut_ptr_range();
let mut src_range = src.as_ptr_range();
let status = unsafe { self.feed_from_raw(&mut dst_range, &mut src_range, false) };
FeedResult {
dst_consumed: unsafe { dst_range.start.offset_from(dst.as_mut_ptr()) } as usize,
src_consumed: unsafe { src_range.start.offset_from(src.as_ptr()) } as usize,
result: common::Error::ok_or_warning(status),
}
}
#[inline(always)]
fn convert_to(&mut self, src: &[Self::FromUnit]) -> Result<Vec<Self::ToUnit>, common::Error> {
let mut buf: Vec<Self::ToUnit> = Vec::with_capacity(src.len());
let mut dst_range = Range {
start: buf.as_mut_ptr(),
end: unsafe { buf.as_mut_ptr().add(buf.capacity()) },
};
let mut src_range = src.as_ptr_range();
loop {
unsafe {
let status = self.feed_to_raw(&mut dst_range, &mut src_range, true);
// calculate how many converted bytes have been written to the buffer to update
// its length
let written_bytes = dst_range.start.offset_from(buf.as_mut_ptr()) as usize;
buf.set_len(written_bytes);
if status != sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR {
// bail out and let the caller handle errors (if there are any)
common::Error::ok_or_warning(status)?;
return Ok(buf);
} else {
// resize capacity
buf.reserve(buf.len());
// ensure dst_range points to new buffer
dst_range = Range {
start: buf.as_mut_ptr().add(buf.len()),
end: buf.as_mut_ptr().add(buf.capacity()),
}
}
}
}
}
#[inline(always)]
fn convert_from(&mut self, src: &[Self::ToUnit]) -> Result<Vec<Self::FromUnit>, common::Error> {
let mut buf: Vec<Self::FromUnit> = Vec::with_capacity(src.len());
let mut dst_range = Range {
start: buf.as_mut_ptr(),
end: unsafe { buf.as_mut_ptr().add(buf.capacity()) },
};
let mut src_range = src.as_ptr_range();
loop {
unsafe {
let status = self.feed_from_raw(&mut dst_range, &mut src_range, true);
// calculate how many converted bytes have been written to the buffer to update
// its length
let written_bytes = dst_range.start.offset_from(buf.as_mut_ptr()) as usize;
buf.set_len(written_bytes);
if status != sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR {
// bail out and let the caller handle errors (if there are any)
common::Error::ok_or_warning(status)?;
return Ok(buf);
} else {
// resize capacity
buf.reserve(buf.len());
// ensure dst_range points to new buffer
dst_range = Range {
start: buf.as_mut_ptr().add(buf.len()),
end: buf.as_mut_ptr().add(buf.capacity()),
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::UConverter;
#[test]
fn test_available_converter_names() {
let converters = available_converters();
let converters_count = converters.len();
let mut count = 0usize;
for _ in converters {
count += 1;
}
assert_eq!(converters_count, count);
}
#[test]
fn test_converter_aliases() {
let aliases = aliases("SHIFT_JIS");
let aliases_count = aliases.len();
let mut count = 0usize;
for _ in aliases {
count += 1;
}
assert_eq!(aliases_count, count);
}
#[test]
fn test_utf8_conversion() {
let mut converter = UConverter::open("UTF-8").unwrap();
let utf8_string = "スーパー";
let utf16_string: Vec<u16> = converter.convert_to_uchars(utf8_string.as_bytes()).unwrap();
assert_eq!(
utf8_string,
std::str::from_utf8(&converter.convert_from_uchars(&utf16_string).unwrap()).unwrap()
);
}
#[test]
fn test_shiftjis_conversion() {
const SHIFT_JIS_STRING: [u8; 8] = [0x83, 0x58, 0x81, 0x5B, 0x83, 0x70, 0x81, 0x5B];
let mut converter = UConverter::open("SHIFT-JIS").unwrap();
let utf16_string = converter.convert_to_uchars(&SHIFT_JIS_STRING).unwrap();
assert_eq!(
SHIFT_JIS_STRING.iter().copied().collect::<Vec<u8>>(),
converter
.convert_from_uchars(utf16_string.as_slice())
.unwrap()
);
}
#[test]
fn test_shiftjis_feeding() {
const UTF8_STRING: &str =
"Shift_JIS(シフトジス)は、コンピュータ上で日本語を含む文字列を表現するために\
用いられる文字コードの一つ。シフトJIS(シフトジス)と表記されることもある。";
let mut converter = UConverter::open("UTF-8").unwrap();
let mut dst_buffer: Vec<u16> = Vec::new();
dst_buffer.resize(1024, 0);
let mut dst_chunks = dst_buffer.chunks_mut(8);
let mut get_dst_chunk = move || dst_chunks.next();
let mut src_chunks = UTF8_STRING.as_bytes().chunks(6);
let mut get_src_chunk = move || src_chunks.next();
let mut dst: &mut [u16] = get_dst_chunk().unwrap();
let mut src: &[u8] = get_src_chunk().unwrap();
loop {
let res = converter.feed_to_uchars(dst, src);
match res.result {
Ok(_) | Err(common::Error::Sys(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR)) => {
dst = dst.split_at_mut(res.dst_consumed).1;
src = src.split_at(res.src_consumed).1;
}
_ => panic!("conversion error"),
}
if dst.is_empty() {
dst = get_dst_chunk().unwrap();
}
if src.is_empty() {
src = match get_src_chunk() {
None => break,
Some(src) => src,
};
}
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ucnv/src/utf8.rs | rust_icu_ucnv/src/utf8.rs | // Copyright 2021 Luis Cáceres
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
std::ops::Range, std::os::raw,
};
use super::{FeedConverterRaw, FeedResult, UConverter};
/// This is a convenience type that provides conversion functions directly to/from UTF-8.
///
/// This type wraps around `ucnv_convertEx`. It keeps two converters for the specified encoding and for
/// UTF-8, as well as the UTF-16 pivot buffers used by `ucnv_convertEx`.
///
/// Its interface is analogous to the interface of [UConverter], so for examples and more detailed
/// information on its use, refer to the documentation page of [UConverter].
///
/// For convenience, the single-string conversion functions take a `&str` for UTF-8 input and
/// give a `String` for UTF-8 output.
#[derive(Debug)]
pub struct Converter {
utf8: UConverter,
converter: UConverter,
pivot_buffer: Box<[sys::UChar]>,
pivot_to: Range<*mut sys::UChar>,
pivot_to_source: *mut sys::UChar,
pivot_to_target: *mut sys::UChar,
pivot_from: Range<*mut sys::UChar>,
pivot_from_source: *mut sys::UChar,
pivot_from_target: *mut sys::UChar,
}
unsafe impl Send for Converter {}
impl Converter {
pub fn open(name: &str) -> Result<Self, common::Error> {
let converter = UConverter::open(name)?;
let utf8 = UConverter::open("UTF-8")?;
let mut pivot_buffer = vec![0u16; 2 * 8192].into_boxed_slice();
let (pivot_to, pivot_from) = pivot_buffer.split_at_mut(8192);
let (pivot_to, pivot_from) = (pivot_to.as_mut_ptr_range(), pivot_from.as_mut_ptr_range());
Ok(Self {
utf8,
converter,
pivot_to_source: pivot_to.start,
pivot_to_target: pivot_to.start,
pivot_to,
pivot_from_source: pivot_from.start,
pivot_from_target: pivot_from.start,
pivot_from,
pivot_buffer,
})
}
pub fn try_clone(&self) -> Result<Self, common::Error> {
let utf8 = self.utf8.try_clone()?;
let converter = self.converter.try_clone()?;
let mut pivot_buffer = self.pivot_buffer.clone();
let (pivot_to, pivot_from) = pivot_buffer.split_at_mut(8192);
let (pivot_to, pivot_from) = (pivot_to.as_mut_ptr_range(), pivot_from.as_mut_ptr_range());
// shift the pivot_{to,from}_{source,target} pointers to point to the newly-created buffer
let pivot_to_source = unsafe {
pivot_to
.start
.offset(self.pivot_to_source.offset_from(self.pivot_to.start))
};
let pivot_to_target = unsafe {
pivot_to
.start
.offset(self.pivot_to_target.offset_from(self.pivot_to.start))
};
let pivot_from_source = unsafe {
pivot_from
.start
.offset(self.pivot_from_source.offset_from(self.pivot_from.start))
};
let pivot_from_target = unsafe {
pivot_from
.start
.offset(self.pivot_from_target.offset_from(self.pivot_from.start))
};
Ok(Self {
utf8,
converter,
pivot_buffer,
pivot_to,
pivot_to_source,
pivot_to_target,
pivot_from,
pivot_from_source,
pivot_from_target,
})
}
#[inline(always)]
pub fn has_ambiguous_mappings(&self) -> bool {
self.converter.has_ambiguous_mappings()
}
#[inline(always)]
pub fn name(&self) -> Result<&str, common::Error> {
self.converter.name()
}
pub fn reset(&mut self) {
self.reset_to_utf8();
self.reset_from_utf8();
}
pub fn reset_to_utf8(&mut self) {
self.converter.reset_to_uchars();
self.utf8.reset_from_uchars();
self.pivot_to_source = self.pivot_to.start;
self.pivot_to_target = self.pivot_to_target;
}
pub fn reset_from_utf8(&mut self) {
self.utf8.reset_to_uchars();
self.converter.reset_from_uchars();
self.pivot_from_source = self.pivot_from.start;
self.pivot_from_target = self.pivot_from_target;
}
pub fn feed_to_utf8(&mut self, dst: &mut [u8], src: &[u8]) -> FeedResult {
self.feed_to(dst, src)
}
pub fn feed_from_utf8(&mut self, dst: &mut [u8], src: &[u8]) -> FeedResult {
self.feed_from(dst, src)
}
pub fn convert_to_utf8(&mut self, src: &[u8]) -> Result<String, common::Error> {
self.reset_to_utf8();
self.convert_to(src)
.map(|v| String::from_utf8(v).expect("should be valid UTF-8"))
}
pub fn convert_from_utf8(&mut self, src: &str) -> Result<Vec<u8>, common::Error> {
self.reset_from_utf8();
self.convert_from(src.as_bytes())
}
}
impl FeedConverterRaw for Converter {
// for utf8
type ToUnit = u8;
// for other encoding
type FromUnit = u8;
unsafe fn feed_to_raw(
&mut self,
dst: &mut Range<*mut Self::ToUnit>,
src: &mut Range<*const Self::FromUnit>,
should_flush: bool,
) -> sys::UErrorCode {
let mut dst_raw = Range {
start: dst.start as *mut raw::c_char,
end: dst.end as *mut raw::c_char,
};
let mut src_raw = Range {
start: src.start as *const raw::c_char,
end: src.end as *const raw::c_char,
};
// ucnv_convertEx documentation indicates it appends a 0-terminator at the end of the
// converted output if possible. This does not advance the dst pointer so we don't need to
// do anything about it.
let mut status = sys::UErrorCode::U_ZERO_ERROR;
versioned_function!(ucnv_convertEx)(
self.utf8.0.as_ptr(),
self.converter.0.as_ptr(),
&mut dst_raw.start,
dst_raw.end,
&mut src_raw.start,
src_raw.end,
self.pivot_to.start,
&mut self.pivot_to_source,
&mut self.pivot_to_target,
self.pivot_to.end,
false.into(),
should_flush.into(),
&mut status,
);
dst.start = dst_raw.start as *mut u8;
src.start = src_raw.start as *const u8;
status
}
unsafe fn feed_from_raw(
&mut self,
dst: &mut Range<*mut Self::FromUnit>,
src: &mut Range<*const Self::ToUnit>,
should_flush: bool,
) -> sys::UErrorCode {
let mut dst_raw = Range {
start: dst.start as *mut raw::c_char,
end: dst.end as *mut raw::c_char,
};
let mut src_raw = Range {
start: src.start as *const raw::c_char,
end: src.end as *const raw::c_char,
};
// ucnv_convertEx documentation indicates it appends a 0-terminator at the end of the
// converted output if possible. This does not advance the dst pointer so we don't need to
// do anything about it.
let mut status = sys::UErrorCode::U_ZERO_ERROR;
versioned_function!(ucnv_convertEx)(
self.converter.0.as_ptr(),
self.utf8.0.as_ptr(),
&mut dst_raw.start,
dst_raw.end,
&mut src_raw.start,
src_raw.end,
self.pivot_from.start,
&mut self.pivot_from_source,
&mut self.pivot_from_target,
self.pivot_from.end,
false.into(),
should_flush.into(),
&mut status,
);
dst.start = dst_raw.start as *mut u8;
src.start = src_raw.start as *const u8;
status
}
}
#[cfg(test)]
mod tests {
use rust_icu_common as common;
use rust_icu_sys as sys;
use super::Converter;
#[test]
fn test_shiftjis_utf8_conversion() {
const SHIFT_JIS_STRING: [u8; 8] = [0x83, 0x58, 0x81, 0x5B, 0x83, 0x70, 0x81, 0x5B];
const UTF8_STRING: &str = "スーパー";
let mut converter = Converter::open("SHIFT-JIS").unwrap();
assert_eq!(
UTF8_STRING,
converter
.convert_to_utf8(&SHIFT_JIS_STRING)
.unwrap()
.as_str()
);
assert_eq!(
SHIFT_JIS_STRING.iter().copied().collect::<Vec<u8>>(),
converter.convert_from_utf8(UTF8_STRING).unwrap()
);
}
#[test]
fn test_shiftjis_utf8_feeding() {
const UTF8_STRING: &str =
"Shift_JIS(シフトジス)は、コンピュータ上で日本語を含む文字列を表現するために\
用いられる文字コードの一つ。シフトJIS(シフトジス)と表記されることもある。";
let mut converter = Converter::open("SHIFT_JIS").unwrap();
let mut dst_buffer: Vec<u8> = Vec::new();
dst_buffer.resize(1024, 0);
let mut dst_chunks = dst_buffer.chunks_mut(8);
let mut get_dst_chunk = move || dst_chunks.next();
let mut src_chunks = UTF8_STRING.as_bytes().chunks(6);
let mut get_src_chunk = move || src_chunks.next();
let mut dst: &mut [u8] = get_dst_chunk().unwrap();
let mut src: &[u8] = get_src_chunk().unwrap();
loop {
let res = converter.feed_from_utf8(dst, src);
match res.result {
Ok(_) | Err(common::Error::Sys(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR)) => {
dst = dst.split_at_mut(res.dst_consumed).1;
src = src.split_at(res.src_consumed).1;
}
_ => panic!("conversion error"),
}
if dst.is_empty() {
dst = get_dst_chunk().unwrap();
}
if src.is_empty() {
src = match get_src_chunk() {
None => break,
Some(src) => src,
};
}
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_common/src/lib.rs | rust_icu_common/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Commonly used functionality adapters.
//!
//! At the moment, this crate contains the declaration of various errors
use {
anyhow::anyhow,
rust_icu_sys as sys,
std::{ffi, os, convert::TryInto},
thiserror::Error,
};
/// Represents a Unicode error, resulting from operations of low-level ICU libraries.
///
/// This is modeled after absl::Status in the Abseil library, which provides ways
/// for users to avoid dealing with all the numerous error codes directly.
#[derive(Error, Debug)]
pub enum Error {
/// The error originating in the underlying sys library.
///
/// At the moment it is possible to produce an Error which has a zero error code (i.e. no
/// error), because it makes it unnecessary for users to deal with error codes directly. It
/// does make for a bit weird API, so we may turn it around a bit. Ideally, it should not be
/// possible to have an Error that isn't really an error.
#[error("ICU error code: {}", _0)]
Sys(sys::UErrorCode),
/// Errors originating from the wrapper code. For example when pre-converting input into
/// UTF8 for input that happens to be malformed.
#[error(transparent)]
Wrapper(#[from] anyhow::Error),
}
impl Error {
/// The error code denoting no error has happened.
pub const OK_CODE: sys::UErrorCode = sys::UErrorCode::U_ZERO_ERROR;
/// Returns true if this error code corresponds to no error.
pub fn is_ok(code: sys::UErrorCode) -> bool {
code == Self::OK_CODE
}
/// Creates a new error from the supplied status. Ok is returned if the error code does not
/// correspond to an error code (as opposed to OK or a warning code).
pub fn ok_or_warning(status: sys::UErrorCode) -> Result<(), Self> {
if Self::is_ok(status) || status < Self::OK_CODE {
Ok(())
} else {
Err(Error::Sys(status))
}
}
/// Creates a new error from the supplied status. Ok is returned if the
/// error code does not constitute an error in preflight mode.
///
/// This error check explicitly ignores the buffer overflow error when reporting whether it
/// contains an error condition.
///
/// Preflight calls to ICU libraries do a read-only scan of the input to determine the buffer
/// sizes required on the output in case of conversion calls such as `ucal_strFromUTF8`. The
/// way this call is made is to offer a zero-capacity buffer (which could be pointed to by a
/// `NULL` pointer), and then call the respective function. The function will compute the
/// buffer size, but will also return a bogus buffer overflow error.
pub fn ok_preflight(status: sys::UErrorCode) -> Result<(), Self> {
if status > Self::OK_CODE && status != sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR {
Err(Error::Sys(status))
} else {
Ok(())
}
}
/// Returns true if this error has the supplied `code`.
pub fn is_code(&self, code: sys::UErrorCode) -> bool {
if let Error::Sys(c) = self {
return *c == code;
}
false
}
/// Returns true if the error is an error, not a warning.
///
/// The ICU4C library has error codes for errors and warnings.
pub fn is_err(&self) -> bool {
match self {
Error::Sys(code) => *code > sys::UErrorCode::U_ZERO_ERROR,
Error::Wrapper(_) => true,
}
}
/// Return true if there was an error in a preflight call.
///
/// This error check explicitly ignores the buffer overflow error when reporting whether it
/// contains an error condition.
///
/// Preflight calls to ICU libraries do a read-only scan of the input to determine the buffer
/// sizes required on the output in case of conversion calls such as `ucal_strFromUTF8`. The
/// way this call is made is to offer a zero-capacity buffer (which could be pointed to by a
/// `NULL` pointer), and then call the respective function. The function will compute the
/// buffer size, but will also return a bogus buffer overflow error.
pub fn is_preflight_err(&self) -> bool {
// We may expand the set of error codes that are exempt from error checks in preflight.
self.is_err() && !self.is_code(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR)
}
/// Returns true if the error is, in fact, a warning (nonfatal).
pub fn is_warn(&self) -> bool {
match self {
Error::Sys(c) => *c < sys::UErrorCode::U_ZERO_ERROR,
_ => false,
}
}
pub fn wrapper(source: impl Into<anyhow::Error>) -> Self {
Self::Wrapper(source.into())
}
}
impl From<ffi::NulError> for Error {
fn from(e: ffi::NulError) -> Self {
Self::wrapper(e)
}
}
impl From<std::str::Utf8Error> for Error {
fn from(e: std::str::Utf8Error) -> Self {
Self::wrapper(e)
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(e: std::string::FromUtf8Error) -> Self {
Self::wrapper(e)
}
}
impl Into<std::fmt::Error> for Error {
fn into(self) -> std::fmt::Error {
// It is not possible to transfer any info into std::fmt::Error, so we log instead.
eprintln!("error while formatting: {:?}", &self);
std::fmt::Error {}
}
}
/// `type_name` is the type to implement drop for.
/// `impl_function_name` is the name of the function that implements
/// memory deallocation. It is assumed that the type has an internal
/// representation wrapped in a [std::ptr::NonNull].
///
/// Example:
///
/// ```rust ignore
/// pub struct UNumberFormatter {
/// rep: std::ptr::NonNull<Foo>,
/// }
/// //...
/// simple_drop_impl!(UNumberFormatter, unumf_close);
/// ```
#[macro_export]
macro_rules! simple_drop_impl {
($type_name:ty, $impl_function_name:ident) => {
impl $crate::__private_do_not_use::Drop for $type_name {
#[doc = concat!("Implements `", stringify!($impl_function_name), "`.")]
fn drop(&mut self) {
unsafe {
$crate::__private_do_not_use::versioned_function!($impl_function_name)
(self.rep.as_ptr());
}
}
}
};
}
/// Helper for calling ICU4C `uloc` methods that require a resizable output string buffer.
pub fn buffered_string_method_with_retry<F>(
mut method_to_call: F,
buffer_capacity: usize,
) -> Result<String, Error>
where
F: FnMut(*mut os::raw::c_char, i32, *mut sys::UErrorCode) -> i32,
{
let mut status = Error::OK_CODE;
let mut buf: Vec<u8> = vec![0; buffer_capacity];
// Requires that any pointers that are passed in are valid.
let full_len: i32 = {
assert!(Error::is_ok(status));
method_to_call(
buf.as_mut_ptr() as *mut os::raw::c_char,
buffer_capacity as i32,
&mut status,
)
};
// ICU methods are inconsistent in whether they silently truncate the output or treat
// the overflow as an error, so we need to check both cases.
if status == sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR ||
(Error::is_ok(status) &&
full_len > buffer_capacity
.try_into()
.map_err(|e| Error::wrapper(e))?) {
status = Error::OK_CODE;
assert!(full_len > 0);
let full_len: usize = full_len
.try_into()
.map_err(|e| Error::wrapper(e))?;
buf.resize(full_len, 0);
// Same unsafe requirements as above, plus full_len must be exactly the output
// buffer size.
{
assert!(Error::is_ok(status));
method_to_call(
buf.as_mut_ptr() as *mut os::raw::c_char,
full_len as i32,
&mut status,
)
};
}
Error::ok_or_warning(status)?;
// Adjust the size of the buffer here.
if full_len >= 0 {
let full_len: usize = full_len
.try_into()
.map_err(|e| Error::wrapper(e))?;
buf.resize(full_len, 0);
}
String::from_utf8(buf).map_err(|e| e.utf8_error().into())
}
/// There is a slew of near-identical method calls which differ in the type of
/// the input argument and the name of the function to invoke.
///
/// The invocation:
///
/// ```rust ignore
/// impl ... {
/// // ...
/// format_ustring_for_type!(format_f64, unum_formatDouble, f64);
/// }
/// ```
///
/// allows us to bind the function:
///
/// ```c++ ignore
/// int32_t unum_formatDouble(
/// const UNumberFormat* fmt,
/// double number,
/// UChar* result,
/// int32_t result_length,
/// UFieldPosition* pos,
/// UErrorCode *status)
/// ```
///
/// as:
///
/// ```rust ignore
/// impl ... {
/// format_f64(&self /* format */, value: f64) -> Result<ustring::UChar, common::Error>;
/// }
/// ```
#[macro_export]
macro_rules! format_ustring_for_type{
($method_name:ident, $function_name:ident, $type_decl:ty) => (
#[doc = concat!("Implements `", stringify!($function_name), "`.")]
pub fn $method_name(&self, number: $type_decl) -> Result<String, common::Error> {
let result = paste::item! {
self. [< $method_name _ustring>] (number)?
};
String::try_from(&result)
}
// Should be able to use https://github.com/google/rust_icu/pull/144 to
// make this even shorter.
paste::item! {
#[doc = concat!("Implements `", stringify!($function_name), "`.")]
pub fn [<$method_name _ustring>] (&self, param: $type_decl) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
[< $method_name _ustring_impl >],
CAPACITY,
[ rep: *const sys::UNumberFormat, param: $type_decl, ],
[ field: *mut sys::UFieldPosition, ]
);
[<$method_name _ustring_impl>](
versioned_function!($function_name),
self.rep.as_ptr(),
param,
// The field position is unused for now.
0 as *mut sys::UFieldPosition,
)
}
}
)
}
/// Expands into a getter method that forwards all its arguments and returns a fallible value which
/// is the same as the value returned by the underlying function.
///
/// The invocation:
///
/// ```rust ignore
/// impl _ {
/// generalized_fallible_getter!(
/// get_context,
/// unum_getContext,
/// [context_type: sys::UDisplayContextType, ],
/// sys::UDisplayContext
/// );
/// }
/// ```
///
/// allows us to bind the function:
///
/// ```c++ ignore
/// UDisplayContext unum_getContext(
/// const SOMETYPE* t,
/// UDisplayContextType type,
/// UErrorCode* status
/// );
/// ```
///
/// which then becomes:
///
/// ```rust ignore
/// impl _ {
/// fn get_context(&self, context_type: sys::UDisplayContextType) -> Result<sys::UDisplayContext, common::Error>;
/// }
/// ```
/// where `Self` has an internal representation named exactly `Self::rep`.
#[macro_export]
macro_rules! generalized_fallible_getter{
($top_level_method_name:ident, $impl_name:ident, [ $( $arg:ident: $arg_type:ty ,)* ], $ret_type:ty) => (
#[doc = concat!("Implements `", stringify!($impl_name), "`.")]
pub fn $top_level_method_name(&self, $( $arg: $arg_type, )* ) -> Result<$ret_type, common::Error> {
let mut status = common::Error::OK_CODE;
let result: $ret_type = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!($impl_name)(self.rep.as_ptr(), $( $arg, )* &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(result)
}
)
}
/// Expands into a setter methods that forwards all its arguments between []'s and returns a
/// Result<(), common::Error>.
///
/// The invocation:
///
/// ```rust ignore
/// impl _ {
/// generalized_fallible_setter!(
/// get_context,
/// unum_getContext,
/// [context_type: sys::UDisplayContextType, ]
/// );
/// }
/// ```
///
/// allows us to bind the function:
///
/// ```c++ ignore
/// UDisplayContext unum_setContext(
/// const SOMETYPE* t,
/// UDisplayContext value,
/// UErrorCode* status
/// );
/// ```
///
/// which then becomes:
///
/// ```rust ignore
/// impl _ {
/// fn set_context(&self, value: sys::UDisplayContext) -> Result<(), common::Error>;
/// }
/// ```
/// where `Self` has an internal representation named exactly `Self::rep`.
#[macro_export]
macro_rules! generalized_fallible_setter{
($top_level_method_name:ident, $impl_name:ident, [ $( $arg:ident : $arg_type:ty, )* ]) => (
generalized_fallible_getter!(
$top_level_method_name,
$impl_name,
[ $( $arg: $arg_type, )* ],
());
)
}
/// Used to simulate an array of C-style strings.
#[derive(Debug)]
pub struct CStringVec {
// The internal representation of the vector of C strings.
rep: Vec<ffi::CString>,
// Same as rep, but converted into C pointers.
c_rep: Vec<*const os::raw::c_char>,
}
impl CStringVec {
/// Creates a new C string vector from the provided rust strings.
///
/// C strings are continuous byte regions that end in `\0` and do not
/// contain `\0` anywhere else.
///
/// Use `as_c_array` to get an unowned raw pointer to the array, to pass
/// into FFI C code.
pub fn new(strings: &[&str]) -> Result<Self, Error> {
let mut rep = Vec::with_capacity(strings.len());
// Convert all to asciiz strings and insert into the vector.
for elem in strings {
let asciiz = ffi::CString::new(*elem)?;
rep.push(asciiz);
}
let c_rep = rep.iter().map(|e| e.as_ptr()).collect();
Ok(CStringVec { rep, c_rep })
}
/// Returns the underlying array of C strings as a C array pointer. The
/// array must not change after construction to ensure that this pointer
/// remains valid.
pub fn as_c_array(&self) -> *const *const os::raw::c_char {
self.c_rep.as_ptr() as *const *const os::raw::c_char
}
/// Returns the number of elements in the vector.
pub fn len(&self) -> usize {
self.rep.len()
}
/// Returns whether the vector is empty.
pub fn is_empty(&self) -> bool {
self.rep.is_empty()
}
}
// Items used by macros. Unstable private API; do not use.
#[doc(hidden)]
pub mod __private_do_not_use {
pub use Drop;
pub use rust_icu_sys::versioned_function;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_code() {
let error = Error::ok_or_warning(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR)
.err()
.unwrap();
assert!(error.is_code(sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR));
assert!(!error.is_preflight_err());
assert!(!error.is_code(sys::UErrorCode::U_ZERO_ERROR));
}
#[test]
fn test_into_char_array() {
let values = vec!["eenie", "meenie", "minie", "moe"];
let c_array = CStringVec::new(&values).expect("success");
assert_eq!(c_array.len(), 4);
}
#[test]
fn test_with_embedded_nul_byte() {
let values = vec!["hell\0x00o"];
let _c_array = CStringVec::new(&values).expect_err("should fail");
}
#[test]
fn test_parser_error_ok() {
let tests = vec![
sys::UParseError {
line: 0,
offset: 0,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
sys::UParseError {
line: -1,
offset: 0,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
sys::UParseError {
line: 0,
offset: -1,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
];
for test in tests {
assert!(parse_ok(test).is_ok(), "for test: {:?}", test.clone());
}
}
#[test]
fn test_parser_error_not_ok() {
let tests = vec![
sys::UParseError {
line: 1,
offset: 0,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
sys::UParseError {
line: 0,
offset: 1,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
sys::UParseError {
line: -1,
offset: 1,
preContext: [0; 16usize],
postContext: [0; 16usize],
},
];
for test in tests {
assert!(parse_ok(test).is_err(), "for test: {:?}", test.clone());
}
}
}
/// A zero-value parse error, used to initialize types that get passed into FFI code.
pub static NO_PARSE_ERROR: sys::UParseError = sys::UParseError {
line: 0,
offset: 0,
preContext: [0; 16usize],
postContext: [0; 16usize],
};
/// Converts a parse error to a Result.
///
/// A parse error is an error if line or offset are positive, apparently.
pub fn parse_ok(e: sys::UParseError) -> Result<(), crate::Error> {
if e.line > 0 || e.offset > 0 {
return Err(Error::Wrapper(anyhow!(
"parse error: line: {}, offset: {}",
e.line,
e.offset
)));
}
Ok(())
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_common/tests/hygiene.rs | rust_icu_common/tests/hygiene.rs | #![no_implicit_prelude]
struct Type {
rep: ::std::ptr::NonNull<::rust_icu_sys::UMessageFormat>,
}
::rust_icu_common::simple_drop_impl!(Type, umsg_close);
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ubrk/src/lib.rs | rust_icu_ubrk/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU text boundary analysis support for Rust
//!
//! This crate provides a Rust implementation of the ICU text boundary analysis APIs
//! in `ubrk.h`. Character (grapheme cluster), word, line-break, and sentence iterators
//! are available.
//!
//! ## Examples
//!
//! Sample code use is given below.
//!
//! ```rust
//! use rust_icu_sys as sys;
//! use rust_icu_ubrk as ubrk;
//!
//! let text = "The lazy dog jumped over the fox.";
//! let mut iter =
//! ubrk::UBreakIterator::try_new(sys::UBreakIteratorType::UBRK_WORD, "en", text)
//! .unwrap();
//!
//! assert!(iter.is_boundary(0));
//! assert_eq!(0, iter.first());
//! assert_eq!(None, iter.previous());
//! assert_eq!(0, iter.current());
//!
//! let text_len = text.len() as i32;
//! assert!(iter.is_boundary(text_len));
//! assert_eq!(iter.last_boundary(), text_len);
//! assert_eq!(None, iter.next());
//! assert_eq!(iter.current(), text_len);
//!
//! let word_start = text.find("jumped").unwrap() as i32;
//! let word_end = word_start + 6;
//! assert!(iter.is_boundary(word_start));
//! assert!(iter.is_boundary(word_end));
//! assert!(!iter.is_boundary(word_start + 3));
//! assert_eq!(word_end, iter.following(word_start + 3));
//! assert_eq!(word_end, iter.current());
//! assert_eq!(Some(word_start), iter.previous());
//! assert_eq!(word_start, iter.current());
//! assert_eq!(Some(word_end), iter.next());
//! assert_eq!(word_end, iter.current());
//! assert_eq!(word_start, iter.preceding(word_start + 3));
//! assert_eq!(word_start, iter.current());
//!
//! // Reset to first boundary and consume `iter`.
//! iter.first();
//! let boundaries: Vec<i32> = iter.collect();
//! assert_eq!(vec![3, 4, 8, 9, 12, 13, 19, 20, 24, 25, 28, 29, 32, 33], boundaries);
//! ```
//!
//! See the [ICU user guide](https://unicode-org.github.io/icu/userguide/boundaryanalysis/)
//! and the C API documentation in the
//! [`ubrk.h` header](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ubrk_8h.html)
//! for details.
use {
rust_icu_common::{self as common, simple_drop_impl},
rust_icu_sys::{self as sys, *},
rust_icu_uloc as uloc, rust_icu_ustring as ustring,
std::{convert::TryFrom, ffi, os::raw, ptr, rc::Rc},
};
/// Returned by break iterator to indicate that all text boundaries have been returned.
// UBRK_DONE is defined as a macro in ICU and macros are not currently supported
// by bindgen, so we define it ourselves here.
pub const UBRK_DONE: i32 = -1;
/// Rust wrapper for the ICU `UBreakIterator` type.
pub struct UBreakIterator {
// Pointer to the underlying ICU representation.
rep: ptr::NonNull<sys::UBreakIterator>,
// The underlying C representation holds pointers to `text` and exactly one of
// {`locale`, `rules`, `binary_rules`} throughout its lifetime. We are
// responsible for ensuring that the pointers remain valid during that time,
// and for dropping the referenced values once the underlying C representation
// is released.
//
// A break iterator may be cloned, in which case the underlying C representation
// of the cloned iterator will hold pointers to the values pointed to by the
// original iterator, while maintaining its own internal iteration state.
//
// For these reasons, these fields are wrapped in `Rc`, ensuring that the
// referenced values (`text`, `locale`, etc.) are not released prematurely
// if the original break iterator is dropped before its clone. As break
// iterators are inherently not thread-safe [1], `Rc` was chosen over `Arc`.
//
// [1] https://unicode-org.github.io/icu/userguide/boundaryanalysis/#thread-safety
text: Rc<ustring::UChar>,
locale: Option<Rc<ffi::CString>>,
rules: Option<Rc<ustring::UChar>>,
binary_rules: Option<Rc<Vec<u8>>>,
}
// Implements `ubrk_close`.
simple_drop_impl!(UBreakIterator, ubrk_close);
impl Iterator for UBreakIterator {
type Item = i32;
/// Advances the break iterator's position to the next boundary after its
/// current position.
///
/// Note that `ubrk_next` will _never_ return the first boundary. For example,
/// given a newly-initialized break iterator whose internal position is `0`,
/// the first invocation of `next` will return the _next_ boundary, not `0`.
/// If the caller requires the first boundary, it should utilize [`first`].
///
/// Also note that interleaving calls to [`first`], [`last_boundary`], [`previous`],
/// [`preceding`], or [`following`] may change the break iterator's internal
/// position, thereby affecting the next value returned by `next`.
///
/// Implements `ubrk_next`.
///
/// [`first`]: #method.first
/// [`following`]: #method.following
/// [`last_boundary`]: #method.last_boundary
/// [`preceding`]: #method.preceding
/// [`previous`]: #method.previous
fn next(&mut self) -> Option<Self::Item> {
let index = unsafe { versioned_function!(ubrk_next)(self.rep.as_ptr()) };
if index == UBRK_DONE {
None
} else {
Some(index)
}
}
}
impl UBreakIterator {
/// Returns an iterator over the locales for which text breaking information
/// is available.
///
/// Implements `ubrk_countAvailable`.
pub fn available_locales() -> Locales {
Locales {
index: 0,
upper: unsafe { versioned_function!(ubrk_countAvailable)() },
}
}
/// Creates a new break iterator with the specified type (character, word,
/// line, or sentence) in the specified locale over `text`.
///
/// Implements `ubrk_open`.
pub fn try_new(
type_: sys::UBreakIteratorType,
locale: &str,
text: &str,
) -> Result<Self, common::Error> {
let text = ustring::UChar::try_from(text)?;
let locale = uloc::ULoc::try_from(locale)?;
Self::try_new_ustring(type_, &locale, &text)
}
/// Implements `ubrk_open`.
pub fn try_new_ustring(
type_: sys::UBreakIteratorType,
locale: &uloc::ULoc,
text: &ustring::UChar,
) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
// Clone text and get locale as a CString for break iterator to own.
let locale = locale.as_c_str();
let text = text.clone();
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_open)(
type_,
locale.as_ptr(),
text.as_c_ptr(),
text.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UBreakIterator);
Ok(Self {
locale: Some(Rc::new(locale)),
rules: None,
binary_rules: None,
text: Rc::new(text),
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Creates a new break iterator using the specified breaking rules.
///
/// See the [ICU user guide](https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html)
/// for rules syntax.
///
/// Implements `ubrk_openRules`.
pub fn try_new_rules(rules: &str, text: &str) -> Result<Self, common::Error> {
let rules = ustring::UChar::try_from(rules)?;
let text = ustring::UChar::try_from(text)?;
Self::try_new_rules_ustring(&rules, &text)
}
/// Implements `ubrk_openRules`.
pub fn try_new_rules_ustring(
rules: &ustring::UChar,
text: &ustring::UChar,
) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let mut parse_status = common::NO_PARSE_ERROR;
// Clone text and rules for break iterator to own.
let rules = rules.clone();
let text = text.clone();
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_openRules)(
rules.as_c_ptr(),
rules.len() as i32,
text.as_c_ptr(),
text.len() as i32,
&mut parse_status,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
common::parse_ok(parse_status)?;
assert_ne!(rep, 0 as *mut sys::UBreakIterator);
Ok(Self {
locale: None,
rules: Some(Rc::new(rules)),
binary_rules: None,
text: Rc::new(text),
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Creates a new break iterator using pre-compiled binary rules.
///
/// Binary rules can be obtained with [`get_binary_rules`].
///
/// [`get_binary_rules`]: #method.get_binary_rules
///
/// Implements `ubrk_openBinaryRules`.
pub fn try_new_binary_rules(rules: &Vec<u8>, text: &str) -> Result<Self, common::Error> {
let text = ustring::UChar::try_from(text)?;
Self::try_new_binary_rules_ustring(rules, &text)
}
/// Implements `ubrk_openBinaryRules`.
pub fn try_new_binary_rules_ustring(
rules: &Vec<u8>,
text: &ustring::UChar,
) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
// Clone text and binary rules for break iterator to own.
let rules = rules.clone();
let text = text.clone();
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_openBinaryRules)(
rules.as_ptr() as *const raw::c_uchar,
rules.len() as i32,
text.as_c_ptr(),
text.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UBreakIterator);
Ok(Self {
locale: None,
rules: None,
binary_rules: Some(Rc::new(rules)),
text: Rc::new(text),
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Returns a `Vec<u8>` containing the compiled binary version of the rules
/// specifying the behavior of this break iterator.
///
/// Implements `ubrk_getBinaryRules`.
pub fn get_binary_rules(&self) -> Result<Vec<u8>, common::Error> {
let mut status = common::Error::OK_CODE;
// Preflight to determine length of buffer for binary rules.
let rules_len = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_getBinaryRules)(
self.rep.as_ptr(),
0 as *mut raw::c_uchar,
0,
&mut status,
)
};
common::Error::ok_preflight(status)?;
// Use determined length to get the actual binary rules.
let mut status = common::Error::OK_CODE;
let mut rules = vec![0; rules_len as usize];
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_getBinaryRules)(
self.rep.as_ptr(),
rules.as_mut_ptr() as *mut raw::c_uchar,
rules_len,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
Ok(rules)
}
/// Performs a clone of the underlying representation.
///
/// The cloned break iterator will hold pointers to the same text, and rules,
/// binary rules, or locale, as the original break iterator. The clone's
/// underlying C representation will maintain its own independent iteration
/// state, but it will be initialized to that of the original (so, for example,
/// if `self.current() == 11`, then `self.safe_clone().current() == 11`).
///
/// Note that the `Clone` trait was not implemented as the underlying operation
/// may fail.
///
/// Implements `ubrk_safeClone`.
pub fn safe_clone(&self) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
versioned_function!(ubrk_safeClone)(
self.rep.as_ptr(),
// The following two parameters, stackBuffer and pBufferSize,
// are deprecated, so we pass NULL pointers.
0 as *mut raw::c_void,
0 as *mut i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UBreakIterator);
Ok(Self {
locale: self.locale.as_ref().map(|x| x.clone()),
rules: self.rules.as_ref().map(|x| x.clone()),
binary_rules: self.binary_rules.as_ref().map(|x| x.clone()),
text: self.text.clone(),
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Instructs this break iterator to point to a new piece of text.
///
/// Implements `ubrk_setText`.
pub fn set_text(&mut self, text: &str) -> Result<(), common::Error> {
let text = ustring::UChar::try_from(text)?;
self.set_text_ustring(&text)
}
/// Implements `ubrk_setText`.
pub fn set_text_ustring(&mut self, text: &ustring::UChar) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
// Clone text and take ownership.
let text = text.clone();
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_setText)(
self.rep.as_ptr(),
text.as_c_ptr(),
text.len() as i32,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
self.text = Rc::new(text);
Ok(())
}
/// Reports the most recently-returned text boundary.
///
/// Implements `ubrk_current`.
pub fn current(&self) -> i32 {
unsafe { versioned_function!(ubrk_current)(self.rep.as_ptr()) }
}
/// Sets the break iterator's position to the boundary preceeding its current
/// position.
///
/// Implements `ubrk_previous`.
pub fn previous(&self) -> Option<i32> {
let result = unsafe { versioned_function!(ubrk_previous)(self.rep.as_ptr()) };
if result == UBRK_DONE {
None
} else {
Some(result)
}
}
/// Moves the iterator to the beginning of its text and returns the new
/// position (zero).
///
/// Implements `ubrk_first`.
pub fn first(&self) -> i32 {
unsafe { versioned_function!(ubrk_first)(self.rep.as_ptr()) }
}
/// Moves the iterator to the position immediately _beyond_ the last character
/// in its text and returns the new position.
///
/// Named as such so as to avoid conflict with the `last` method provided by
/// `Iterator`.
///
/// Implements `ubrk_last`.
pub fn last_boundary(&self) -> i32 {
unsafe { versioned_function!(ubrk_last)(self.rep.as_ptr()) }
}
/// Moves the iterator to the boundary immediately preceding the specified offset
/// and returns the new position.
///
/// Implements `ubrk_preceding`.
pub fn preceding(&self, offset: i32) -> i32 {
unsafe { versioned_function!(ubrk_preceding)(self.rep.as_ptr(), offset) }
}
/// Moves the iterator to the boundary immediately following the specified offset
/// and returns the new position.
///
/// Implements `ubrk_following`.
pub fn following(&self, offset: i32) -> i32 {
unsafe { versioned_function!(ubrk_following)(self.rep.as_ptr(), offset) }
}
/// Reports whether the specified offset is a boundary.
///
/// Implements `ubrk_isBoundary`.
pub fn is_boundary(&self, offset: i32) -> bool {
let result: sys::UBool =
unsafe { versioned_function!(ubrk_isBoundary)(self.rep.as_ptr(), offset) };
result != 0
}
/// Returns the locale, valid or actual, of this break iterator.
///
/// Implements `ubrk_getLocaleByType`.
pub fn get_locale_by_type(
&self,
type_: sys::ULocDataLocaleType,
) -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
let char_ptr = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_getLocaleByType)(self.rep.as_ptr(), type_, &mut status)
};
common::Error::ok_or_warning(status)?;
let c_str = unsafe { ffi::CStr::from_ptr(char_ptr) };
let s = c_str.to_str().map(|s| s.to_owned())?;
Ok(s)
}
/// Returns the status of the break rule that determined the most-recently
/// returned boundary. The default status for rules that do not explicitly
/// provide one is zero.
///
/// See the [ICU user guide](https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html)
/// for details on rule syntax and rule status values.
///
/// Implements `ubrk_getRuleStatus`.
pub fn get_rule_status(&self) -> i32 {
unsafe { versioned_function!(ubrk_getRuleStatus)(self.rep.as_ptr()) }
}
/// Returns the statuses of the break rules that determined the most-recently
/// returned boundary. The default status for rules that do not explicitly
/// provide one is zero.
///
/// See the [ICU user guide](https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html)
/// for details on rule syntax and rule status values.
///
/// Implements `ubrk_getRuleStatusVec`.
pub fn get_rule_status_vec(&self) -> Result<Vec<i32>, common::Error> {
let mut status = common::Error::OK_CODE;
// Preflight to determine buffer size.
let rules_len = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_getRuleStatusVec)(
self.rep.as_ptr(),
0 as *mut i32,
0,
&mut status,
)
};
common::Error::ok_preflight(status)?;
let mut status = common::Error::OK_CODE;
let mut rules: Vec<i32> = vec![0; rules_len as usize];
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ubrk_getRuleStatusVec)(
self.rep.as_ptr(),
rules.as_mut_ptr(),
rules_len,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
Ok(rules)
}
}
/// Iterator over the locales for which text breaking information is available.
pub struct Locales {
// The index to be passed to `ubrk_getAvailable` on the next call to `next`.
index: i32,
// The number of available locales; the result of `ubrk_countAvailable`.
upper: i32,
}
impl Iterator for Locales {
type Item = uloc::ULoc;
/// Returns the next locale for which text breaking information is available.
///
/// Implements `ubrk_getAvailable`.
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.upper {
return None;
}
let loc_ptr = unsafe { versioned_function!(ubrk_getAvailable)(self.index) };
assert_ne!(loc_ptr, 0 as *const raw::c_char);
let c_str = unsafe { ffi::CStr::from_ptr(loc_ptr) };
let loc = uloc::ULoc::try_from(c_str);
match loc {
Ok(loc) => {
self.index += 1;
Some(loc)
}
_ => None,
}
}
}
impl ExactSizeIterator for Locales {
/// Reports the number of locales for which text breaking information is available.
///
/// Implements `ubrk_countAvailable`.
fn len(&self) -> usize {
self.upper as usize
}
}
#[cfg(test)]
mod tests {
use super::UBreakIterator;
use log::trace;
use rust_icu_sys::{self as sys, UBreakIteratorType::*, ULocDataLocaleType::*};
use std::{convert::TryFrom, rc::Rc};
// Wraps a `UBreakIterator` to emit Strings formed by pairs of word boundaries.
struct Words<'a> {
iter: &'a mut UBreakIterator,
chars: Vec<sys::UChar>,
}
impl<'a> Words<'a> {
fn new(iter: &'a mut UBreakIterator) -> Self {
let text = String::try_from(&*iter.text).unwrap();
Self {
iter,
chars: text.as_str().encode_utf16().collect::<Vec<_>>(),
}
}
}
impl<'a> Iterator for Words<'a> {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
let start = self.iter.current();
self.iter.next().and_then(|end| {
String::from_utf16(&self.chars[(start as usize)..(end as usize)]).ok()
})
}
}
const TEXT: &str = r#""It wasn't the wine," murmured Mr. Snodgrass. "It was the salmon.""#;
#[test]
fn test_iteration() {
let mut break_iter = UBreakIterator::try_new(UBRK_WORD, "en", TEXT).unwrap();
assert!(break_iter.is_boundary(0));
assert_eq!(0, break_iter.first());
assert_eq!(None, break_iter.previous());
assert_eq!(0, break_iter.current());
let word_start = TEXT.find("murmured").unwrap() as i32;
let word_end = word_start + 8;
assert!(break_iter.is_boundary(word_start));
assert!(break_iter.is_boundary(word_end));
assert!(!break_iter.is_boundary(word_start + 3));
assert_eq!(word_end, break_iter.following(word_start + 3));
assert_eq!(word_end, break_iter.current());
assert_eq!(Some(word_start), break_iter.previous());
assert_eq!(word_start, break_iter.current());
assert_eq!(Some(word_end), break_iter.next());
assert_eq!(word_end, break_iter.current());
assert_eq!(word_start, break_iter.preceding(word_start + 3));
assert_eq!(word_start, break_iter.current());
let text_len = TEXT.len() as i32;
assert!(break_iter.is_boundary(text_len));
assert_eq!(text_len, break_iter.last_boundary());
assert_eq!(None, break_iter.next());
assert_eq!(text_len, break_iter.current());
break_iter.first();
let word_iter = Words::new(&mut break_iter);
assert_eq!(
vec![
"\"",
"It",
" ",
"wasn't",
" ",
"the",
" ",
"wine",
",",
"\"",
" ",
"murmured",
" ",
"Mr",
".",
" ",
"Snodgrass",
".",
" ",
"\"",
"It",
" ",
"was",
" ",
"the",
" ",
"salmon",
".",
"\"",
]
.into_iter()
.map(String::from)
.collect::<Vec<_>>(),
word_iter.collect::<Vec<_>>()
);
}
#[test]
fn test_binary_rules() {
let iter1 = UBreakIterator::try_new(UBRK_WORD, "en", TEXT).unwrap();
let iter1_binary_rules = iter1.get_binary_rules().unwrap();
let iter1_boundaries: Vec<i32> = iter1.collect();
let iter2 = UBreakIterator::try_new_binary_rules(&iter1_binary_rules, TEXT).unwrap();
let iter2_boundaries: Vec<i32> = iter2.collect();
assert!(!iter2_boundaries.is_empty());
assert_eq!(iter1_boundaries, iter2_boundaries);
}
#[test]
fn test_rules() {
let rules = r#"
# Our custom break rules: break on `w`s.
!!chain;
!!quoted_literals_only;
$w = [w];
$not_w = [^w];
$not_w+; # No breaks between code points other than `w`.
$w+ {99}; # Break on `w`s with custom rule status of `99`.
"#;
let mut break_iter = UBreakIterator::try_new_rules(rules, TEXT).unwrap();
#[derive(Debug)]
struct TestCase {
boundary: Option<i32>,
rule_status: i32,
}
let tests = vec![
TestCase {
boundary: Some(4),
rule_status: 0,
},
TestCase {
boundary: Some(5),
rule_status: 99,
},
TestCase {
boundary: Some(15),
rule_status: 0,
},
TestCase {
boundary: Some(16),
rule_status: 99,
},
TestCase {
boundary: Some(50),
rule_status: 0,
},
TestCase {
boundary: Some(51),
rule_status: 99,
},
TestCase {
boundary: Some(66),
rule_status: 0,
},
TestCase {
boundary: None,
rule_status: 0,
},
];
for test in tests {
assert_eq!(test.boundary, break_iter.next());
assert_eq!(test.rule_status, break_iter.get_rule_status());
assert_eq!(
vec![test.rule_status],
break_iter.get_rule_status_vec().unwrap()
);
}
break_iter.first();
let word_iter = Words::new(&mut break_iter);
assert_eq!(
vec![
"\"It ",
"w",
"asn't the ",
"w",
"ine,\" murmured Mr. Snodgrass. \"It ",
"w",
"as the salmon.\"",
]
.into_iter()
.map(String::from)
.collect::<Vec<_>>(),
word_iter.collect::<Vec<_>>(),
);
}
#[test]
fn test_clone() {
let mut iter1 = UBreakIterator::try_new(UBRK_WORD, "en", TEXT).unwrap();
iter1.first();
assert_eq!(1, Rc::strong_count(&iter1.text));
assert_eq!(1, Rc::strong_count(iter1.locale.as_ref().unwrap()));
assert_eq!(Some(1), iter1.next());
assert_eq!(Some(3), iter1.next());
assert_eq!(3, iter1.current());
// Clone in a new scope.
{
let mut iter2 = iter1.safe_clone().unwrap();
assert_eq!(2, Rc::strong_count(&iter1.text));
assert_eq!(2, Rc::strong_count(iter1.locale.as_ref().unwrap()));
assert_eq!(3, iter2.current());
assert_eq!(0, iter2.first());
assert_eq!(Some(1), iter2.next());
assert_eq!(Some(4), iter1.next());
}
assert_eq!(1, Rc::strong_count(&iter1.text));
assert_eq!(1, Rc::strong_count(iter1.locale.as_ref().unwrap()));
assert_eq!(4, iter1.current());
assert_eq!(Some(10), iter1.next());
}
#[test]
fn test_set_text() {
let mut iter = UBreakIterator::try_new(UBRK_WORD, "en", TEXT).unwrap();
let iter_text_rc = iter.text.clone();
assert_eq!(2, Rc::strong_count(&iter_text_rc));
let pos = TEXT.find("murmured").unwrap() as i32;
assert_eq!(pos, iter.preceding(pos + 3));
assert_eq!(pos, iter.current());
let new_str = "The lazy dog.";
iter.set_text(new_str).unwrap();
assert_eq!(1, Rc::strong_count(&iter_text_rc));
assert_eq!(new_str, String::try_from(&*iter.text).unwrap());
assert_eq!(0, iter.current());
assert_eq!(new_str.len() as i32, iter.last_boundary());
}
#[test]
fn test_get_locale_by_type() {
let iter = UBreakIterator::try_new(UBRK_WORD, "en_US_CA@lb=strict", TEXT).unwrap();
// The "valid locale" is the most specific locale supported by ICU, given
// what was requested.
assert_eq!("en_US", iter.get_locale_by_type(ULOC_VALID_LOCALE).unwrap(),);
// The "actual locale" is the locale that breaking information actually comes from.
// In most cases this will be "root".
assert_eq!("root", iter.get_locale_by_type(ULOC_ACTUAL_LOCALE).unwrap(),);
}
#[test]
fn test_available_locales() {
trace!("Available locales");
for loc in UBreakIterator::available_locales() {
trace!(" {}", loc);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_utrans/src/lib.rs | rust_icu_utrans/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU transliteration support for Rust
//!
//! This crate provides a Rust implementation of the ICU transliteration APIs in `utrans.h`.
//!
//! ## Examples
//!
//! Sample code use is given below.
//!
//! ICU includes a number of built-in transliterators, which can be listed with
//! [`get_ids`](#method.get_ids).
//! Transliterators may be combined to form a sequence of text transformations by provding a
//! compound identifier as shown below.
//!
//! ```rust
//! use rust_icu_sys as sys;
//! use rust_icu_utrans as utrans;
//!
//! let compound_id = "NFC; Latin; Latin-ASCII";
//! let ascii_trans = utrans::UTransliterator::new(
//! compound_id, None, sys::UTransDirection::UTRANS_FORWARD).unwrap();
//! assert_eq!(ascii_trans.transliterate("литература").unwrap(), "literatura");
//! ```
//!
//! It is also possible to define your own transliterators by providing a set of rules to
//! [`new`](#method.new).
//!
//! ```rust
//! use rust_icu_sys as sys;
//! use rust_icu_utrans as utrans;
//!
//! let id = "Coffee";
//! let rules = r"a > o; f > ff; \u00e9 > ee;";
//! let custom_trans = utrans::UTransliterator::new(
//! id, Some(rules), sys::UTransDirection::UTRANS_FORWARD).unwrap();
//! assert_eq!(custom_trans.transliterate("caf\u{00e9}").unwrap(), "coffee");
//! ```
//!
//! See the [ICU user guide](https://unicode-org.github.io/icu/userguide/transforms/general/)
//! and the C API documentation in the
//! [`utrans.h` header](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/utrans_8h.html)
//! for details.
use {
rust_icu_common::{self as common, simple_drop_impl},
rust_icu_sys::{self as sys, *},
rust_icu_uenum as uenum, rust_icu_ustring as ustring,
std::{convert::TryFrom, ptr, slice},
};
/// Rust wrapper for the ICU `UTransliterator` type.
#[derive(Debug)]
pub struct UTransliterator {
rep: ptr::NonNull<sys::UTransliterator>,
}
// Implements `utrans_close`.
simple_drop_impl!(UTransliterator, utrans_close);
impl Clone for UTransliterator {
/// Implements `utrans_clone`.
fn clone(&self) -> Self {
UTransliterator {
rep: self.rep.clone(),
}
}
}
impl UTransliterator {
/// Returns an enumeration containing the identifiers of all available
/// transliterators.
///
/// Implements `utrans_openIDs`.
pub fn get_ids() -> Result<uenum::Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_openIDs)(&mut status)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UEnumeration);
// utrans_openIDs returns a pointer to an ICU UEnumeration, which we
// are now responsible for closing, so we wrap it in its corresponding
// rust_icu type.
let ids = unsafe { uenum::Enumeration::from_raw_parts(None, rep) };
Ok(ids)
}
/// Consumes `trans` and registers it with the underlying ICU system.
/// A transliterator that has been registered with the system can be
/// retrieved by calling [`new`](#method.new) with its identifier.
///
/// Implements `utrans_register`.
pub fn register(trans: Self) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_register)(trans.rep.as_ptr(), &mut status)
}
common::Error::ok_or_warning(status)?;
// ICU4C now owns the transliterator and is responsible for closing it,
// so we avoid dropping a resource we don't own.
std::mem::forget(trans);
Ok(())
}
/// If rules are given, creates a new transliterator with rules and identifier.
/// Otherwise, returns the ICU system transliterator with the given identifier.
///
/// Implements `utrans_openU`.
pub fn new(
id: &str,
rules: Option<&str>,
dir: sys::UTransDirection,
) -> Result<Self, common::Error> {
let id = ustring::UChar::try_from(id)?;
let rules = match rules {
Some(s) => Some(ustring::UChar::try_from(s)?),
None => None,
};
Self::new_ustring(&id, rules.as_ref(), dir)
}
/// Implements `utrans_openU`.
pub fn new_ustring(
id: &ustring::UChar,
rules: Option<&ustring::UChar>,
dir: sys::UTransDirection,
) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let mut parse_status = common::NO_PARSE_ERROR.clone();
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_openU)(
id.as_c_ptr(),
id.len() as i32,
dir,
rules.map_or(0 as *const sys::UChar, |r| r.as_c_ptr()),
rules.as_ref().map_or(0, |r| r.len()) as i32,
&mut parse_status,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
common::parse_ok(parse_status)?;
assert_ne!(rep, 0 as *mut sys::UTransliterator);
Ok(Self {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Returns the identifier for this transliterator.
///
/// Implements `utrans_getUnicodeID`.
pub fn get_id(&self) -> Result<String, common::Error> {
let mut id_len: i32 = 0;
let rep =
unsafe { versioned_function!(utrans_getUnicodeID)(self.rep.as_ptr(), &mut id_len) };
assert_ne!(rep, 0 as *const sys::UChar);
let id_buf = unsafe { slice::from_raw_parts(rep, id_len as usize) }.to_vec();
let id = ustring::UChar::from(id_buf);
String::try_from(&id)
}
/// Returns the inverse of this transliterator, provided that the inverse
/// has been registered with the underlying ICU system, i.e., a built-in
/// ICU transliterator or one registered with [`register`](#method.register).
///
/// Implements `utrans_openInverse`.
pub fn inverse(&self) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_openInverse)(self.rep.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UTransliterator);
Ok(Self {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Returns a rules string for this transliterator in the same format
/// expected by [`new`](#method.new).
///
/// Implements `utrans_toRules`.
pub fn to_rules(&self, escape_unprintable: bool) -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
// Preflight to determine length of rules text.
let rules_len = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_toRules)(
self.rep.as_ptr(),
escape_unprintable as sys::UBool,
0 as *mut sys::UChar,
0,
&mut status,
)
};
common::Error::ok_preflight(status)?;
let mut status = common::Error::OK_CODE;
let mut rules: Vec<sys::UChar> = vec![0; rules_len as usize];
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_toRules)(
self.rep.as_ptr(),
escape_unprintable as sys::UBool,
rules.as_mut_ptr(),
rules_len,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
let rules = ustring::UChar::from(rules);
String::try_from(&rules)
}
/// Apply a filter to this transliterator, causing certain characters to
/// pass through untouched. The filter is formatted as a
/// [UnicodeSet](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html)
/// string. If the filter is `None`, then any previously-applied filter
/// is cleared.
///
/// Implements `utrans_setFilter`.
pub fn set_filter(&mut self, pattern: Option<&str>) -> Result<(), common::Error> {
let pattern = match pattern {
Some(s) => Some(ustring::UChar::try_from(s)?),
None => None,
};
self.set_filter_ustring(pattern.as_ref())
}
/// Implements `utrans_setFilter`.
pub fn set_filter_ustring(
&mut self,
pattern: Option<&ustring::UChar>,
) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_setFilter)(
self.rep.as_ptr(),
pattern.map_or(0 as *const sys::UChar, |p| p.as_c_ptr()),
pattern.as_ref().map_or(0, |p| p.len()) as i32,
&mut status,
)
}
common::Error::ok_or_warning(status)
}
/// Returns a string containing the transliterated text.
///
/// Implements `utrans_transUChars`.
pub fn transliterate(&self, text: &str) -> Result<String, common::Error> {
let text = ustring::UChar::try_from(text)?;
let trans_text = self.transliterate_ustring(&text)?;
String::try_from(&trans_text)
}
/// Implements `utrans_transUChars`.
pub fn transliterate_ustring(
&self,
text: &ustring::UChar,
) -> Result<ustring::UChar, common::Error> {
let start: i32 = 0;
let text_len = text.len() as i32;
let mut trans_text = text.clone();
let mut trans_text_len = text_len;
let mut limit = text_len;
let mut status = common::Error::OK_CODE;
// Text is transliterated in place, serving as both the source text and
// the destination buffer for transliterated text. Because transliteration
// may produce text that is longer than the source text, we preflight
// in case of buffer overflow.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_transUChars)(
self.rep.as_ptr(),
trans_text.as_mut_c_ptr(),
&mut trans_text_len,
text_len,
start,
&mut limit,
&mut status,
)
}
common::Error::ok_preflight(status)?;
if trans_text_len > text_len {
// Transliterated text is longer than source text, so resize buffer
// and try again.
trans_text = text.clone();
trans_text.resize(trans_text_len as usize);
limit = text_len;
let mut status = common::Error::OK_CODE;
let mut length = text_len;
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utrans_transUChars)(
self.rep.as_ptr(),
trans_text.as_mut_c_ptr(),
&mut length,
trans_text_len as i32,
start,
&mut limit,
&mut status,
)
}
common::Error::ok_or_warning(status)?;
}
if trans_text.len() > limit as usize {
// Transliterated text is shorter than source text, so truncate
// buffer to new length.
trans_text.resize(limit as usize);
}
Ok(trans_text)
}
/// Unregister a transliterator from the underlying ICU system.
///
/// Implements `utrans_unregisterID`.
pub fn unregister(id: &str) -> Result<(), common::Error> {
let id = ustring::UChar::try_from(id)?;
unsafe { versioned_function!(utrans_unregisterID)(id.as_c_ptr(), id.len() as i32) }
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::sys;
use super::UTransliterator;
use log::trace;
const DIR_FWD: sys::UTransDirection = sys::UTransDirection::UTRANS_FORWARD;
const DIR_REV: sys::UTransDirection = sys::UTransDirection::UTRANS_REVERSE;
#[ignore]
#[test]
fn test_builtin() {
trace!("Available IDs");
let ids = UTransliterator::get_ids().unwrap().map(|r| r.unwrap());
for id in ids {
trace!(" {}", id);
}
let id = "NFC;Cyrillic-Latin;Latin-ASCII";
let trans = UTransliterator::new(id, None, DIR_FWD).unwrap();
assert_eq!(trans.get_id().unwrap(), id);
// "цäfé" (6) -> "cafe" (4)
let text = "\u{0446}a\u{0308}fe\u{0301}";
assert_eq!(text.chars().count(), 6);
assert_eq!(trans.transliterate(text).unwrap(), "cafe");
}
#[test]
fn test_inverse() {
let trans = UTransliterator::new("Latin-ASCII", None, DIR_FWD).unwrap();
let inverse = trans.inverse().unwrap();
assert_eq!(inverse.get_id().unwrap(), "ASCII-Latin");
}
#[test]
fn test_rules_based() {
let rules = "a <> xyz;";
let fwd_trans = UTransliterator::new("MyA-MyXYZ", Some(rules), DIR_FWD).unwrap();
assert_eq!(fwd_trans.transliterate("abc").unwrap(), "xyzbc");
let rev_trans = UTransliterator::new("MyXYZ-MyA", Some(rules), DIR_REV).unwrap();
assert_eq!(rev_trans.transliterate("xyzbc").unwrap(), "abc");
}
#[test]
fn test_to_rules() {
let id = "MyA-MyXYZ";
let rules = "a > xyz;";
let trans = UTransliterator::new(id, Some(rules), DIR_FWD).unwrap();
assert_eq!(trans.to_rules(false).unwrap(), rules);
}
#[test]
fn test_set_filter() {
let id = "MyABC-MyXYZ";
let rules = "{a}bc > x; x{b}c > y; xy{c} > z;";
let mut trans = UTransliterator::new(id, Some(rules), DIR_FWD).unwrap();
trans.set_filter(Some("[ac]")).unwrap();
assert_eq!(trans.transliterate("abc").unwrap(), "xbc");
trans.set_filter(None).unwrap();
assert_eq!(trans.transliterate("abc").unwrap(), "xyz");
}
#[ignore]
#[test]
fn test_register_unregister() {
let count_available = || UTransliterator::get_ids().unwrap().count();
let initial_count = count_available();
let id = "MyA-MyXYZ";
let rules = "a > xyz;";
let trans = UTransliterator::new(&id, Some(&rules), DIR_FWD).unwrap();
UTransliterator::register(trans).unwrap();
assert_eq!(count_available(), initial_count + 1);
UTransliterator::unregister(id).unwrap();
assert_eq!(count_available(), initial_count);
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/proposals/ecma402_listformat/src/lib.rs | proposals/ecma402_listformat/src/lib.rs | #![doc(html_playground_url = "https://play.rust-lang.org")]
//! # The ECMA 402 abstract API surface proposal for `Intl.ListFormat`
//!
//! *fmil@google.com\
//! Created: 2020-05-28\
//! Last updated: 2020-06-09*
//!
//! This proposal is an elaboration of the article [Meta-proposal: Towards common ECMA 402 API
//! surface for Rust][meta1]. It contains traits declarations for a rust-flavored
//! [ECMA-402 API][ecma402api].
//!
//! [ecma402api]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
//! [meta1]: https://github.com/unicode-org/icu4x/blob/%6d%61%73%74%65%72/proposals/pr001-ecma402.md
//!
//! ## A note about presentation
//!
//! This proposal is deliberately written in the form of compilable rust code, and is perhaps best
//! consumed by looking at the output of the command `cargo doc --open` ran at the top level
//! directory. Such a presentation allows us to embed live code inline with the text, which can
//! be readily tested by clicking the "Run" button:
//!
//! ```rust
//! println!("Hello Unicode! ❤️!");
//! ```
//!
//! It's not quite [literate
//! programming](https://en.wikipedia.org/wiki/Literate_programming) but should be close enough for
//! getting a general feel for how the API will be used, and allows to follow the text together
//! with the presentation.
//!
//! ## Approach
//!
//! As outlined in the [meta-proposal][meta1approach], we will first test the feasibility of an
//! ECMA-402 API with a minimal example. [`Intl.ListFormat`][listformat] was chosen. It is
//! a very small API surface with few configuration options compared to other members of the same
//! API family, while in general it is very similar to all other functions in the [`Intl`
//! library][intl].
//!
//! [meta1approach]: https://github.com/unicode-org/icu4x/blob/%6d%61%73%74%65%72/proposals/pr001-ecma402.md#approach
//! [listformat]:
//! https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat
//! [intl]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
//!
//! # A closer look at `Intl.ListFormat`
//!
//! A [quick example of `Intl.ListFormat` use][lfquick] in JavaScript is shown below, for
//! completeness and as a baseline for comparison.
//!
//! [lfquick]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat
//!
//! ```js
//! const vehicles = ['Motorcycle', 'Bus', 'Car'];
//!
//! const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
//! console.log(formatter.format(vehicles));
//! // expected output: "Motorcycle, Bus, and Car"
//! ```
//!
//! Per [MDN][lfquick], disregarding the JavaScript declaration overhead, the following functions
//! are the focus:
//!
//! | | Description |
//! |--|--|
//! | `Intl.supportedLocalesOf() => [String]` | Creates a ListFormat object, initialized for the given locale and options set |
//! | `Intl.ListFormat(locale..., options) => <ListFormat object>` | Creates a ListFormat object, initialized for the given locale and options set |
//! | `<ListFormat object>.format([element,...]) => <String>` | Formats the list of `element`s according to the formatting rules for `locale` that the `<ListFormat object>` was initialized with. |
//! | `<ListFormat object>.formatToParts([element,...]) => [String]` | Formats the list of `element`s according to the formatting rules for `locale` that the `<ListFormat object>` was initialized with. |
//!
//! The options are as follows (details omitted here, refer to [MDN][lfquick]):
//!
//! | | Values |
//! |--|--|
//! | `locale` | [BCP 47][bcp47] language tag for the locale actually used. |
//! | `style` | One of `long`, `short`, `narrow` |
//! | `type` | One of `conjunction`, `disjunction` |
//!
//! [bcp47]: https://tools.ietf.org/html/bcp47
//!
//! # `Intl.ListFormat` API proposal in Rust
//!
//! This section presents a condensed view of the implementation for `ListFormat` in Rust. Please
//! see the section [Considerations](#considerations) for the design rationale.
//!
//! Implementation fragments, consult each link for specific on each of the items below:
//! - [Locale] trait (better name pending).
//! - [listformat] mod.
//! - [listformat::options] mod.
//! - [listformat::Format] trait.
//!
//! # Considerations
//!
//! ## Names, names
//!
//! Naming is always fun. This proposal is presented as a crate `ecma402_listformat`, but is
//! intended to be re-exported from a top-level crate with a name such as `ecma402::listformat`.
//!
//! This gives the following sample options uses, which can be lenthened to avoid ambiguity.
//!
//! ```rust ignore
//! use ecma402::listformat::options::In;
//! use ecma402::listformat::options::Style;
//! // ... etc
//! ```
//!
//! ## Options handling
//!
//! The configuration options may be the easy bits. The style and type are probably simple enough
//! to define in place, instead of delegating that to the implementor. We define them in a new
//! mod, to keep the `Style` and `Type` names free for reuse for other parts of the API surface.
//! Not all options can be packaged this way, some require an open ended set of possible elements
//! (of which some may be well-formed but invalid, for example).
//!
//! `Style` and `Type` are concrete types, since those are fixed by the API.
//!
//! ```rust
//! /// Deliberately placed in a separate mod, to make for ergonomic naming. Short
//! /// names are a personal preference: `options::Style` reads better to me than
//! /// `OptionsStyle` or such. It does not seem in strife with ECMA-402, since
//! /// it says nothing about types at all.
//! mod options {
//! pub enum Style {
//! Long, Short, Narrow,
//! }
//! pub enum Type {
//! Conjunction, Disjunction,
//! }
//! /// These are the options that go in.
//! /// Use as `options::In`. I happen to like short names on types that
//! /// have the same name as the mod they are in, to reduce repetition.
//! pub struct In {
//! pub style: Style,
//! /// `type` is a reserved word. Better suggestions welcome.
//! pub in_type: Type,
//! }
//! }
//! ```
//!
//! You would refer to them by `listformat::options::Style::Long` and the like, which gives us
//! non-repetitive and reusable names. `use` clauses can be used to shorten if needed:
//!
//! ```rust ignore
//! use listformat::options::Style;
//! // ...
//! ```
//!
//! ## Locale
//!
//! Passing in a locale specifier is the first nontrivial design decision. This is since locales
//! may be implemented in a number of different ways:
//!
//! 1. Is the locale data owned or borrowed?
//! 1. Are locales fallible or infallible? I.e. are they *well-formed* or always *valid*.
//! 1. Do locales come from a system repository or are they somehow provided by the end user?
//!
//! In Rust, each of these concerns seems to ask for different interfaces, making general
//! interfaces hard to formulate. I welcome a correction here if I'm wrong. The objective is to
//! unify as many as possible of the above use cases in a trait that can express all of them.
//!
//! ### "Stringly typed" API
//!
//! One possibility is to require a string-like type (`AsRef<str>`).
//!
//! Pros:
//!
//! * This is the closest to the JavaScript API surface
//! * It is the easiest one to implement.
//!
//! Cons:
//!
//! * It has the loosest guarantees as to the functionality it provides.
//! * It implies convertibility to a string-like object, which may require allocation.
//!
//! This approach is inferior compared to the Formatting API because it forces
//! the user's hand in string use. A better alternative is below.
//!
//! ### Formatting API
//!
//! The formatting API is just the following:
//!
//! ```rust
//! use std::fmt;
//! use std::hash;
//! pub trait Locale: fmt::Display + hash::Hash {
//! // We may extend this with more functionality.
//! };
//! ```
//!
//! Pros:
//!
//! * Simplicity
//! * Defers the decision on how to format the `Locale` and delegates it to
//! the user.
//!
//! Cons:
//!
//! * Assumes that on-screen display of a `Locale` is the same as string
//! serialization of the locale.
//!
//! We believe that this conflation is not an issue today, as the same effective
//! approach is already being used in Gecko.
//!
//! ## Error handling
//!
//! It is conceivable that a method call could return an error. As error reporting is fairly cheap
//! in Rust, returning `Result<_, E>` for `E` being some error type, should be expected and
//! natural. The to make this useful, `E` should probably be constrained to a standard "error
//! reporting" type such as `std::error::Error`.
//!
//! This suggests a general error handling approach:
//!
//! ```rust
//! use std::error;
//! pub trait Trait {
//! type Error: error::Error;
//! fn function() -> Result<(), Self::Error>;
//! }
//! ```
//!
//! Pros:
//!
//! - A standardized error reporting type.
//! - Allows the use of crates such as [`anyhow`](https://crates.io/crates/anyhow).
//!
//! Cons:
//!
//! - Requires `Trait::Error` to implement a potentially hefty trait `std::error::Error`.
//! - There can be only one implementation of `Trait` in a library. In this case it seems
//! that may be enough.
//!
//! ### Fallibility
//!
//! The issue of fallibility in the API comes up because an implementor can decide to implement
//! lazy checking of the constructed collaborator types. A `LocaleIdentifier` type is one of
//! those types. While [`Locale`][lid] validates its inputs, [`rust_icu_uloc::ULoc`][uloc] does
//! not: in fact, almost all of its operations are fallible, and there does not seem to be a way to
//! validate `ULoc` eagerly, the way the underlying ICU4C API is defined.
//!
//! [lid]: https://github.com/unicode-org/icu4x/pull/47
//! [uloc]: https://docs.rs/rust_icu_uloc/0.2.2/rust_icu_uloc/struct.ULoc.html
//!
//! Now since `Intl.supportedLocalesOf()` exists, could say that that any user will have
//! the chance to obtain a valid locale either by taking one from the list of supported locales,
//! or by language-matching desired locale with the list of supported locales ahead of time.
//!
//! This means that an infallible API could work for the case of `Intl.ListFormat`. However,
//! we do not want to rely on a locale resolution protocol imposed by the end user. Furthermore,
//! not all combination of input options will be valid across all constructors of `Intl.*` types.
//! With this in mind
//!
//! > Note: Previous versions of this proposal had an infallible constructor `new`. This has been
//! determined to be infeasible, and a fallible constructor `try_new` has been put in place
//! instead.
//!
//! ```rust ignore
//! let loc = rust_icu_uloc::ULoc::try_from("nl-NL").expect("locale accepted");
//! let formatter = ecma402::listformat::Format::try_new(
//! &loc, ecma402::listformat::options::In{ /* ... */ }).expect("formatter constructed");
//! ```
//!
//! ## Sequences as input parameters
//!
//! This section concerns input parameters that are sequences. The general approach is to
//! defer the forming of the sequence and use `IntoIterator` to pass the values in like so:
//!
//! ```rust
//! // This is the trait that our objects will implement.
//! pub trait Trait {}
//!
//! pub trait Api {
//! fn function<'a, T>(input: impl IntoIterator<Item=&'a T>)
//! where T: Trait + 'a;
//! }
//! ```
//!
//! This approach does not work for output parameters returned in a trait, however. An approach
//! for that is given below.
//!
//! ## Iteration over output parameters
//!
//! Next up, let's take a look at how output iteration (iterators as return types) may be
//! traitified.
//!
//! We are exploring this
//! because APIs that require iteration may naturally come out of data items that contain
//! sequences; such as the [variant subtags][vartags]. And since generic iteration may be
//! of more general interest, we explore it in a broader context.
//!
//! [vartags]: http://unicode.org/reports/tr35/#unicode_variant_subtag
//!
//! Generic iteration seems somewhat complicated to express in a Rust trait.
//! [unic_langid::LanguageIdentifier`][ulangid], for example, has the following method:
//!
//! [ulangid]: https://docs.rs/unic-langid/0.9.0/unic_langid/struct.LanguageIdentifier.html#method.variants
//!
//! ```rust ignore
//! pub fn variants(&self) -> impl ExactSizeIterator
//! ```
//!
//! This expresses quite a natural need to iterate over the specified variants of a locale.
//! We would very much like to traitify this function so that different implementors could
//! contribute their own. The straightforward approach won't fly:
//!
//! ```rust
//! // This will not compile:
//! // "`impl Trait` not alowed outside of function and inherent method return types"
//! use core::iter::ExactSizeIterator;
//! pub trait Trait {
//! fn variants() -> impl ExactSizeIterator;
//! }
//! ```
//!
//! A second attempt fails too:
//!
//! ```rust
//! // This will not compile:
//! // error[E0191]: the value of the associated type `Item`
//! // (from trait `std::iter::Iterator`) must be specified
//! use core::iter::ExactSizeIterator;
//! pub trait Trait {
//! fn variants() -> dyn ExactSizeIterator;
//! }
//! ```
//!
//! Of course this is all invalid Rust, but it was a naive attempt to express a seemingly natural
//! idea of "I'd like this trait to return me an iterator over some string-like objects".
//!
//! Here's more exhibits for the gallery of failed approaches:
//!
//! ```rust
//! // This will not compile:
//! // error[E0191]: the value of the associated type `Item`
//! // (from trait `std::iter::Iterator`) must be specified
//! use core::iter::ExactSizeIterator;
//! pub trait Trait {
//! fn variants() -> Box<dyn ExactSizeIterator>;
//! }
//! ```
//!
//! This has a couple of problems:
//!
//! 1. E0191, requiring a concrete associated type as an iterator `Item`, which we don't have.
//! 2. If we were to bind `Item` to a concrete type, we would have made that type obligatory
//! for all the implementors.
//! 3. [Box] requires an allocation, which is not useful for `#![no_std]` (without alloc).
//!
//! Even if we disregard (3), then (2) will get us. The following snippet compiles, but
//! forever fixes the associated iteration type to `String`. Any implementors that don't
//! implement variants as strings are out of luck.
//!
//! ```rust
//! use core::iter::ExactSizeIterator;
//! pub trait Trait {
//! // Oops... associated type is fixed now.
//! fn variants() -> Box<dyn ExactSizeIterator<Item=String>>;
//! }
//! ```
//!
//! Trying to be clever with genericizing the type also gets us nowhere. This works, but
//! requires a `Box`, which in turn requires a change to the type signature of
//! `LanguageIdentifier::variants()`.
//!
//! ```rust
//! use core::iter::ExactSizeIterator;
//! pub trait Trait {
//! type IterItem;
//! fn variants() -> Box<dyn ExactSizeIterator<Item=Self::IterItem>>;
//! }
//! ```
//!
//! Getting to a generic iterator that doesn't require a box is a piece of gymnastics. Getting
//! to an iterable of owned strings requires the iterating trait to be implemented over
//! *a lifetime-scoped reference* of the implementing type.
//!
//! ```rust
//! pub trait Variants {
//! /// The type of the item yieled by the iterator returned by [Variants::variants]. Note
//! /// that [Variants::Variant] may be a reference to the type stored in the iterator.
//! type Variant;
//! /// The type of the iterator returned by [Variants::variants].
//! type Iter: ExactSizeIterator<Item = Self::Variant>;
//! fn variants(self) -> Self::Iter;
//! }
//!
//! // Here's how to implement the trait when the underlying type is borrowed.
//!
//! pub struct BorrowedVariant {
//! variants: Vec<&'static str>,
//! }
//!
//! impl<'a> Variants for &'a BorrowedVariant {
//! type Variant = &'a &'a str;
//! type Iter = std::slice::Iter<'a, &'a str>;
//! fn variants(self) -> Self::Iter {
//! self.variants.iter()
//! }
//! }
//!
//! let borrowed = BorrowedVariant{ variants: vec!["a", "b"], };
//! assert_eq!(
//! vec!["a", "b"],
//! borrowed.variants()
//! .map(|v| v.to_owned().to_owned())
//! .collect::<Vec<String>>(),
//! );
//!
//! // Here is how to implement the trait when the underlying type is owned.
//!
//! pub struct OwnedVariant {
//! variants: Vec<String>,
//! }
//!
//! impl<'a> Variants for &'a OwnedVariant {
//! type Variant = &'a String;
//! type Iter = std::slice::Iter<'a, String>;
//! fn variants(self) -> Self::Iter {
//! self.variants.iter()
//! }
//! }
//!
//! let owned = OwnedVariant{ variants: vec!["a".to_string(), "b".to_string()], };
//! assert_eq!(
//! vec!["a", "b"],
//! owned.variants()
//! .map(|v| v.to_owned())
//! .collect::<Vec<String>>(),
//! );
//! ```
use std::fmt;
/// This trait contains the common features of the Locale object that must be shared among
/// all the implementations. Every implementor of `listformat` should provide their
/// own version of [Locale], and should ensure that it implements [Locale]. as
/// specified here.
///
/// For the time being we agreed that a [Locale] *must* be convertible into its string
/// form, using `Display`.
pub trait Locale: fmt::Display {}
/// The [listformat] mod contains all the needed implementation bits for `Intl.ListFormat`.
///
/// > Note: This is not yet the entire API. I'd like to get to a consensus on what has been
/// defined, then use the patterns adopted here for the rest.
pub mod listformat {
/// Contains the API configuration as prescribed by ECMA 402.
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [Format::try_new]
/// for the use of the options.
pub mod options {
/// Chooses the list formatting approach.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Style {
Long,
Short,
Narrow,
}
/// Chooses between "this, that and other", and "this, that or other".
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
/// "This, that and other".
Conjunction,
/// "This, that or other".
Disjunction,
}
}
/// The options set by the user at construction time. See discussion at the top level
/// about the name choice. Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
///
/// The default values of all the options are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Options {
/// Selects a [options::Style] for the formatted list. If unset, defaults
/// to [options::Style::Long].
pub style: options::Style,
/// Selects a [options::Type] for the formatted list. If unset, defaults to
/// [options::Type::Conjunction].
pub in_type: options::Type,
}
/// Allows the use of `listformat::Format::try_new(..., Default::default())`.
impl Default for Options {
/// Gets the default values of [Options] if omitted at setup. The
/// default values are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
fn default() -> Self {
Options {
style: options::Style::Long,
in_type: options::Type::Conjunction,
}
}
}
use std::fmt;
/// The package workhorse: formats supplied pieces of text into an ergonomically formatted
/// list.
///
/// While ECMA 402 originally has functions under `Intl`, we probably want to
/// obtain a separate factory from each implementor.
///
/// Purposely omitted:
///
/// - `supported_locales_of`.
pub trait Format {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [Format].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new(l: impl crate::Locale, opts: Options) -> Result<Self, Self::Error>
where
Self: std::marker::Sized;
/// Formats `list` into the supplied standard `writer` [fmt::Write].
///
/// The original [ECMA 402 function][ecma402fmt] returns a string. This is likely the only
/// reasonably generic option in JavaScript so it is adequate. In Rust, however, it is
/// possible to pass in a standard formatting strategy (through `writer`).
///
/// [ecma402fmt]:
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format
///
/// This makes it unnecessary for [Format] to implement its own, and can
/// completely avoid constructing any intermediary representation. This, in turn,
/// allows the user to provide a purpose built formatter, or a custom one if needed.
///
/// A purpose built formatter could be one that formats into a fixed-size buffer; or
/// another that knows how to format strings into a DOM. If ECMA 402 compatibility is
/// needed, the user can force formatting into a string by passing the appropriate
/// formatter.
///
/// > Note:
/// > - Should there be a convenience method that prints to string specifically?
/// > - Do we need `format_into_parts`?
fn format<I, L, W>(self, list: L, writer: &mut W) -> fmt::Result
where
I: fmt::Display,
L: IntoIterator<Item = I>,
W: fmt::Write;
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ucsdet/src/lib.rs | rust_icu_ucsdet/src/lib.rs | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU character set detection support for rust
//!
//! This crate provides character set detection based on the detection
//! functions implemented by the ICU library, specifically in
//! the [header `ucsdet.h`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ucsdet_8h.html).
//!
//! This crate provides two main type: [CharsetDetector] and [CharsetMatch],
//! [CharsetDetector] can detect text and return a [CharsetMatch].
//!
//! For more information on ICU character set detection, please see also:
//! [character set detection documentation on the ICU user guide](https://unicode-org.github.io/icu/userguide/conversion/detection.html).
//!
//! > Are you missing some features from this crate? Consider [reporting an
//! issue](https://github.com/google/rust_icu/issues) or even [contributing the
//! functionality](https://github.com/google/rust_icu/pulls).
use {
common::simple_drop_impl,
rust_icu_common as common, rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_uenum::Enumeration,
std::{
ffi::CStr,
marker::PhantomData,
mem::transmute,
os::raw::c_char,
ptr::{self, NonNull},
},
};
#[allow(unused_imports)]
use sys::*;
/// This interface wraps around icu4c `UCharsetDetector`.
#[derive(Debug)]
pub struct CharsetDetector<'detector> {
rep: ptr::NonNull<sys::UCharsetDetector>,
_marker: PhantomData<&'detector ()>,
}
simple_drop_impl!(CharsetDetector<'_>, ucsdet_close);
impl<'detector> CharsetDetector<'detector> {
/// Try to create a charset detector
pub fn new() -> Result<CharsetDetector<'detector>, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let rep = unsafe { versioned_function!(ucsdet_open)(&mut status) };
common::Error::ok_or_warning(status)?;
let result = CharsetDetector {
rep: ptr::NonNull::new(rep).unwrap(),
_marker: PhantomData,
};
Ok(result)
}
/// Get an iterator over the set of all detectable charsets
///
/// See also: [Enumeration]
pub fn available_charsets(&self) -> Result<Enumeration, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let raw_enum = unsafe {
versioned_function!(ucsdet_getAllDetectableCharsets)(self.rep.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
assert!(!raw_enum.is_null());
Ok(unsafe { Enumeration::from_raw_parts(None, raw_enum) })
}
/// Set text for detection
///
/// `text` should live longer than [self].
pub fn set_text<'b: 'detector>(&mut self, text: &'b [u8]) -> Result<(), common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
unsafe {
versioned_function!(ucsdet_setText)(
self.rep.as_ptr(),
text.as_ptr() as *const c_char,
text.len() as i32,
&mut status,
);
}
common::Error::ok_or_warning(status)
}
/// Set the declared encoding for the charset detection.
pub fn set_declared_encoding(&self, encoding: &str) -> Result<(), common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
unsafe {
versioned_function!(ucsdet_setDeclaredEncoding)(
self.rep.as_ptr(),
encoding.as_ptr() as *const c_char,
encoding.len() as i32,
&mut status,
);
}
common::Error::ok_or_warning(status)
}
/// Return the charset that best matches the supplied input data.
pub fn detect(&self) -> Result<CharsetMatch, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let charset_match =
unsafe { versioned_function!(ucsdet_detect)(self.rep.as_ptr(), &mut status) };
common::Error::ok_or_warning(status)?;
Ok(CharsetMatch {
rep: NonNull::new(charset_match as *mut _).unwrap(),
contrain: PhantomData,
})
}
/// Find all charset matches that appear to be consistent
/// with the input, returning an array of results.
///
/// The results are ordered with the best quality match first.
///
/// Returns `&[CharsetMatch]` if no error.
pub fn detect_all(&self) -> Result<&[CharsetMatch], common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let mut len = 0;
let charset_match = unsafe {
versioned_function!(ucsdet_detectAll)(self.rep.as_ptr(), &mut len, &mut status)
};
common::Error::ok_or_warning(status)?;
if len == 0 {
return Ok(&[]);
}
let slice = unsafe { std::slice::from_raw_parts_mut(charset_match, len as usize) };
for ele in slice.iter() {
assert!(!ele.is_null())
}
// SAFETY: `CharsetMatch` is marked as `#[repr(transparent)]`, and
// all pointers are checked non-null pointer, so it's safe to transmute
let slice: &[CharsetMatch] = unsafe { transmute(slice) };
Ok(slice)
}
/// Returns the previous setting
pub fn set_input_filter(&self, enable: bool) -> Result<bool, common::Error> {
let charset_match = unsafe {
versioned_function!(ucsdet_enableInputFilter)(self.rep.as_ptr(), enable as i8)
};
Ok(charset_match == 1)
}
/// Enable/disable input filter
pub fn input_filter_enabled(&self) -> bool {
let charset_match =
unsafe { versioned_function!(ucsdet_isInputFilterEnabled)(self.rep.as_ptr()) };
charset_match == 1
}
}
/// Representing a match that was identified from a charset detection operation
///
/// Owned by [CharsetDetector]
#[repr(transparent)]
pub struct CharsetMatch<'detector> {
rep: ptr::NonNull<sys::UCharsetMatch>,
contrain: PhantomData<&'detector ()>,
}
impl<'charset> ::core::fmt::Debug for CharsetMatch<'charset> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
f.debug_struct("CharsetMatch")
.field("name", &self.name())
.field("language", &self.language())
.field("confidence", &self.confidence())
.finish()
}
}
impl<'charset> CharsetMatch<'charset> {
/// Returns the name of the charset
pub fn name(&self) -> Result<&str, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let raw_name = unsafe {
let ptr = versioned_function!(ucsdet_getName)(self.rep.as_ptr(), &mut status);
common::Error::ok_or_warning(status)?;
assert!(!ptr.is_null());
CStr::from_ptr(ptr)
};
Ok(raw_name.to_str()?)
}
/// Returns the RFC 3066 code for the language of the charset
pub fn language(&self) -> Result<&str, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let raw_name = unsafe {
let ptr = versioned_function!(ucsdet_getLanguage)(self.rep.as_ptr(), &mut status);
common::Error::ok_or_warning(status)?;
assert!(!ptr.is_null());
CStr::from_ptr(ptr)
};
Ok(raw_name.to_str()?)
}
/// Get a confidence number for the quality of the match
pub fn confidence(&self) -> Result<i32, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let confidence =
unsafe { versioned_function!(ucsdet_getConfidence)(self.rep.as_ptr(), &mut status) };
Ok(confidence)
}
/// Get the entire input text as a UChar string, placing it into
/// a caller-supplied buffer
pub fn get_uchars(&self, buf: &mut [sys::UChar]) -> Result<usize, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let len = unsafe {
versioned_function!(ucsdet_getUChars)(
self.rep.as_ptr(),
buf.as_mut_ptr(),
buf.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(len as usize)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_available_charsets() {
let ucsd = CharsetDetector::new().unwrap();
for ele in ucsd.available_charsets().unwrap() {
assert!(ele.unwrap().is_ascii())
}
}
#[test]
fn test_charset_detect_shift_jis() {
let mut ucsd = CharsetDetector::new().unwrap();
const SHIFT_JIS_STRING: &[u8] = &[
0x82, 0xB1, 0x82, 0xF1, 0x82, 0xCE, 0x82, 0xF1, 0x82, 0xCD, 0x95, 0xBD, 0x89, 0xBC,
0x96, 0xBC, 0x82, 0xB1, 0x82, 0xF1, 0x82, 0xCE, 0x82, 0xF1, 0x82, 0xCD, 0x95, 0xBD,
0x89, 0xBC, 0x96, 0xBC, 0x82, 0xB1, 0x82, 0xF1, 0x82, 0xCE, 0x82, 0xF1, 0x82, 0xCD,
0x95, 0xBD, 0x89, 0xBC, 0x96, 0xBC,
];
ucsd.set_text(&SHIFT_JIS_STRING).unwrap();
let detected = ucsd.detect().unwrap();
assert_eq!(detected.name().unwrap(), "Shift_JIS");
assert_eq!(detected.language().unwrap(), "ja");
assert!(detected.confidence().unwrap() > 80);
}
#[test]
fn test_charset_detect_all_utf8() {
let mut ucsd = CharsetDetector::new().unwrap();
ucsd.set_text(b"Hello World UTF-8").unwrap();
let detected = ucsd.detect_all().unwrap();
assert!(detected
.into_iter()
.any(|charset| charset.name().unwrap() == "UTF-8"))
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ecma402/src/lib.rs | rust_icu_ecma402/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use rust_icu_uloc::ULoc;
/// Implements ECMA-402 [`Intl.ListFormat`][link].
///
/// [link]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat
pub mod listformat;
/// Implements ECMA-402 [`Intl.PluralRules`][link].
///
/// [link]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRulres/PluralRules
pub mod pluralrules;
/// Implements ECMA-402 [`Intl.NumberFormat`][link].
///
/// [link]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
pub mod numberformat;
/// Implements ECMA-402 [`Intl.DateTimeFormat`][link].
///
/// [link]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
pub mod datetimeformat;
pub enum Locale {
FromULoc(ULoc),
}
impl ecma402_traits::Locale for crate::Locale {}
impl std::fmt::Display for Locale {
/// Implementation that delegates printing the locale to the underlying
/// `rust_icu` implementation.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Locale::FromULoc(ref l) => write!(f, "{}", l),
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ecma402/src/numberformat.rs | rust_icu_ecma402/src/numberformat.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implements the traits found in [ecma402_traits::numberformat].
use {
ecma402_traits, rust_icu_common as common, rust_icu_unumberformatter as unumf,
std::convert::TryInto, std::fmt,
};
#[derive(Debug)]
pub struct NumberFormat {
// The internal representation of number formatting.
rep: unumf::UNumberFormatter,
}
pub(crate) mod internal {
use {
ecma402_traits::numberformat, ecma402_traits::numberformat::options,
rust_icu_common as common,
};
/// Produces a [skeleton][skel] that corresponds to the given option.
///
/// The conversion may fail if the options are malformed, for example request currency
/// formatting but do not have a currency defined.
///
/// [skel]: https://github.com/unicode-org/icu/blob/%6d%61%73%74%65%72/docs/userguide/format_parse/numbers/skeletons.md
pub fn skeleton_from(opts: &numberformat::Options) -> Result<String, common::Error> {
let mut skel: Vec<String> = vec![];
if let Some(ref c) = opts.compact_display {
match c {
options::CompactDisplay::Long => skel.push("compact-long".into()),
options::CompactDisplay::Short => skel.push("compact-short".into()),
}
}
match opts.style {
options::Style::Currency => {
match opts.currency {
None => {
return Err(common::Error::Wrapper(anyhow::anyhow!(
"currency not specified"
)));
}
Some(ref c) => {
skel.push(format!("currency/{}", &c.0));
}
}
match opts.currency_display {
options::CurrencyDisplay::Symbol => {
skel.push(format!("unit-width-short"));
}
options::CurrencyDisplay::NarrowSymbol => {
skel.push(format!("unit-width-narrow"));
}
options::CurrencyDisplay::Code => {
skel.push(format!("unit-width-iso-code"));
}
options::CurrencyDisplay::Name => {
skel.push(format!("unit-width-full-name"));
}
}
match opts.currency_sign {
options::CurrencySign::Accounting => {
skel.push(format!("sign-accounting"));
}
options::CurrencySign::Standard => {
// No special setup here.
}
}
}
options::Style::Unit => match opts.unit {
None => {
return Err(common::Error::Wrapper(anyhow::anyhow!(
"unit not specified"
)));
}
Some(ref u) => {
skel.push(format!("measure-unit/{}", &u.0));
}
},
options::Style::Percent => {
skel.push(format!("percent"));
}
options::Style::Decimal => {
// Default, no special setup needed, apparently.
}
}
match opts.notation {
options::Notation::Standard => {
// Nothing is needed here.
}
options::Notation::Engineering => match opts.sign_display {
options::SignDisplay::Auto => {
skel.push(format!("scientific/*ee"));
}
options::SignDisplay::Always => {
skel.push(format!("scientific/*ee/sign-always"));
}
options::SignDisplay::Never => {
skel.push(format!("scientific/*ee/sign-never"));
}
options::SignDisplay::ExceptZero => {
skel.push(format!("scientific/*ee/sign-expect-zero"));
}
},
options::Notation::Scientific => {
skel.push(format!("scientific"));
}
options::Notation::Compact => {
// ?? Is this true?
skel.push(format!("compact-short"));
}
}
if let Some(ref n) = opts.numbering_system {
skel.push(format!("numbering-system/{}", &n.0));
}
if opts.notation != options::Notation::Engineering {
match opts.sign_display {
options::SignDisplay::Auto => {
skel.push("sign-auto".into());
}
options::SignDisplay::Never => {
skel.push("sign-never".into());
}
options::SignDisplay::Always => {
skel.push("sign-always".into());
}
options::SignDisplay::ExceptZero => {
skel.push("sign-always".into());
}
}
}
let minimum_integer_digits = opts.minimum_integer_digits.unwrap_or(1);
// TODO: this should match the list at:
// https://www.currency-iso.org/en/home/tables/table-a1.html
let minimum_fraction_digits = opts.minimum_fraction_digits.unwrap_or(match opts.style {
options::Style::Currency => 2,
_ => 0,
});
let maximum_fraction_digits = opts.maximum_fraction_digits.unwrap_or(match opts.style {
options::Style::Currency => std::cmp::max(2, minimum_fraction_digits),
_ => 3,
});
let minimum_significant_digits = opts.minimum_significant_digits.unwrap_or(1);
let maximum_significant_digits = opts.maximum_significant_digits.unwrap_or(21);
// TODO: add skeleton items for min and max integer, fraction and significant digits.
skel.push(integer_digits(minimum_integer_digits as usize));
skel.push(fraction_digits(
minimum_fraction_digits as usize,
maximum_fraction_digits as usize,
minimum_significant_digits as usize,
maximum_significant_digits as usize,
));
Ok(skel.iter().map(|s| format!("{} ", s)).collect())
}
// Returns the skeleton annotation for integer width
// 1 -> "integer-width/*0"
// 3 -> "integer-width/*000"
fn integer_digits(digits: usize) -> String {
let zeroes: String = std::iter::repeat("0").take(digits).collect();
#[cfg(feature = "icu_version_67_plus")]
return format!("integer-width/*{}", zeroes);
#[cfg(not(feature = "icu_version_67_plus"))]
return format!("integer-width/+{}", zeroes);
}
fn fraction_digits(min: usize, max: usize, min_sig: usize, max_sig: usize) -> String {
eprintln!(
"fraction_digits: min: {}, max: {} min_sig: {}, max_sig: {}",
min, max, min_sig, max_sig
);
assert!(min <= max, "fraction_digits: min: {}, max: {}", min, max);
let zeroes: String = std::iter::repeat("0").take(min).collect();
let hashes: String = std::iter::repeat("#").take(max - min).collect();
assert!(
min_sig <= max_sig,
"significant_digits: min: {}, max: {}",
min_sig,
max_sig
);
let ats: String = std::iter::repeat("@").take(min_sig).collect();
let hashes_sig: String = std::iter::repeat("#").take(max_sig - min_sig).collect();
return format!(".{}{}/{}{}", zeroes, hashes, ats, hashes_sig,);
}
#[cfg(test)]
mod testing {
use super::*;
#[test]
fn fraction_digits_skeleton_fragment() {
assert_eq!(fraction_digits(0, 3, 1, 21), ".###/@####################");
assert_eq!(fraction_digits(2, 2, 1, 21), ".00/@####################");
assert_eq!(fraction_digits(0, 0, 0, 0), "./");
assert_eq!(fraction_digits(0, 3, 3, 3), ".###/@@@");
}
}
}
impl ecma402_traits::numberformat::NumberFormat for NumberFormat {
type Error = common::Error;
/// Creates a new [NumberFormat].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: ecma402_traits::numberformat::Options) -> Result<Self, Self::Error>
where
L: ecma402_traits::Locale,
Self: Sized,
{
let locale = format!("{}", l);
let skeleton: String = internal::skeleton_from(&opts)?;
let rep = unumf::UNumberFormatter::try_new(&skeleton, &locale)?;
Ok(NumberFormat { rep })
}
/// Formats the plural class of `number` into the supplied `writer`.
///
/// The function implements [`Intl.NumberFormat`][plr] from [ECMA 402][ecma].
///
/// [plr]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn format<W>(&self, number: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write,
{
let result = self.rep.format_double(number).map_err(|e| e.into())?;
let result_str: String = result.try_into().map_err(|e: common::Error| e.into())?;
write!(writer, "{}", result_str)
}
}
#[cfg(test)]
mod testing {
use super::*;
use ecma402_traits::numberformat;
use ecma402_traits::numberformat::NumberFormat;
use rust_icu_uloc as uloc;
use std::convert::TryFrom;
#[test]
fn formatting() {
#[derive(Debug, Clone)]
struct TestCase {
locale: &'static str,
opts: numberformat::Options,
numbers: Vec<f64>,
expected: Vec<&'static str>,
}
let tests = vec![
TestCase {
locale: "sr-RS",
opts: Default::default(),
numbers: vec![
0.0, 1.0, -1.0, 1.5, -1.5, 100.0, 1000.0, 10000.0, 123456.789,
],
expected: vec![
"0",
"1",
"-1",
"1,5",
"-1,5",
"100",
"1.000",
"10.000",
"123.456,789",
],
},
TestCase {
locale: "de-DE",
opts: numberformat::Options {
style: numberformat::options::Style::Currency,
currency: Some("EUR".into()),
..Default::default()
},
numbers: vec![123456.789],
expected: vec!["123.456,79\u{a0}€"],
},
TestCase {
locale: "ja-JP",
opts: numberformat::Options {
style: numberformat::options::Style::Currency,
currency: Some("JPY".into()),
// This is the default for JPY, but we don't consult the
// currency list.
minimum_fraction_digits: Some(0),
maximum_fraction_digits: Some(0),
..Default::default()
},
numbers: vec![123456.789],
expected: vec!["¥123,457"],
},
// TODO: This ends up being a syntax error, why?
//TestCase {
//locale: "en-IN",
//opts: numberformat::Options {
//maximum_significant_digits: Some(3),
//..Default::default()
//},
//numbers: vec![123456.789],
//expected: vec!["1,23,000"],
//},
];
for test in tests {
let locale = crate::Locale::FromULoc(
uloc::ULoc::try_from(test.locale).expect(&format!("locale exists: {:?}", &test)),
);
let format = crate::numberformat::NumberFormat::try_new(locale, test.clone().opts)
.expect(&format!("try_from should succeed: {:?}", &test));
let actual = test
.numbers
.iter()
.map(|n| {
let mut result = String::new();
format
.format(*n, &mut result)
.expect(&format!("formatting succeeded for: {:?}", &test));
result
})
.collect::<Vec<String>>();
assert_eq!(
test.expected, actual,
"\n\tfor test case: {:?},\n\tformat: {:?}",
&test, &format
);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ecma402/src/listformat.rs | rust_icu_ecma402/src/listformat.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implements the traits found in [ecma402_traits::listformat].
use ecma402_traits;
use ecma402_traits::listformat;
use rust_icu_common as common;
use rust_icu_ulistformatter as ulfmt;
use std::fmt;
/// Implements [listformat::Format] using ICU as the underlying implementing library.
#[derive(Debug)]
pub struct Format {
rep: ulfmt::UListFormatter,
}
// Full support for styled formatting is available since v67.
#[cfg(feature = "icu_version_67_plus")]
pub(crate) mod internal {
use ecma402_traits::listformat::options;
use rust_icu_sys as usys;
// Converts the param types from ECMA-402 into ICU.
pub fn to_icu_width(style: &options::Style) -> usys::UListFormatterWidth {
use options::Style;
use usys::UListFormatterWidth;
match style {
Style::Long => UListFormatterWidth::ULISTFMT_WIDTH_WIDE,
Style::Short => UListFormatterWidth::ULISTFMT_WIDTH_SHORT,
Style::Narrow => UListFormatterWidth::ULISTFMT_WIDTH_NARROW,
}
}
// Converts the Type param from ECMA-402 into ICU.
pub fn to_icu_type(in_type: &options::Type) -> usys::UListFormatterType {
use options::Type;
use usys::UListFormatterType;
match in_type {
Type::Conjunction => UListFormatterType::ULISTFMT_TYPE_AND,
Type::Disjunction => UListFormatterType::ULISTFMT_TYPE_OR,
}
}
}
impl listformat::Format for Format {
type Error = common::Error;
/// Creates a new [Format], from a [ecma402_traits::Locale] and [listformat::Options].
fn try_new<L: ecma402_traits::Locale>(
l: L,
_opts: listformat::Options,
) -> Result<Format, Self::Error> {
let locale = format!("{}", l);
#[cfg(feature = "icu_version_67_plus")]
{
let width = internal::to_icu_width(&_opts.style);
let in_type = internal::to_icu_type(&_opts.in_type);
let rep = ulfmt::UListFormatter::try_new_styled(&locale, in_type, width)?;
Ok(Format { rep })
}
// The non-v67 implementation is less featureful.
#[cfg(not(feature = "icu_version_67_plus"))]
{
let rep = ulfmt::UListFormatter::try_new(&locale)?;
Ok(Format { rep })
}
}
/// Formats the given string.
fn format<I, L, W>(&self, list: L, f: &mut W) -> fmt::Result
where
I: fmt::Display,
L: IntoIterator<Item = I>,
W: fmt::Write,
{
// This is an extremely naive implementation: collects the list into
// a slice and formats that thing.
let list_str: Vec<String> = list.into_iter().map(|e| format!("{}", e)).collect();
let refs: Vec<&str> = list_str.iter().map(|e| e.as_str()).collect();
let result = self.rep.format(&refs[..]).map_err(|e| e.into())?;
write!(f, "{}", result)
}
}
#[cfg(test)]
mod testing {
use super::*;
use ecma402_traits;
use ecma402_traits::listformat;
use ecma402_traits::listformat::Format;
use rust_icu_uloc as uloc;
use std::convert::TryFrom;
#[test]
fn test_formatting_table() {
use listformat::options::{Style, Type};
#[derive(Debug)]
struct TestCase {
locale: &'static str,
array: Vec<&'static str>,
opts: listformat::Options,
expected: &'static str,
}
let tests = vec![
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options::default(),
expected: "eenie, meenie, minie, and moe",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Short,
in_type: Type::Conjunction,
},
expected: "eenie, meenie, minie, & moe",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Short,
in_type: Type::Disjunction,
},
expected: "eenie, meenie, minie, or moe",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Narrow,
in_type: Type::Conjunction,
},
expected: "eenie, meenie, minie, moe",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Narrow,
in_type: Type::Disjunction,
},
expected: "eenie, meenie, minie, or moe",
},
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Long,
in_type: Type::Conjunction,
},
expected: "eenie, meenie, minie, and moe",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "en-US",
array: vec!["eenie", "meenie", "minie", "moe"],
opts: listformat::Options {
style: Style::Long,
in_type: Type::Disjunction,
},
expected: "eenie, meenie, minie, or moe",
},
// Try another sample locale.
//
TestCase {
locale: "sr-RS",
array: vec!["Раја", "Гаја", "Влаја"],
opts: listformat::Options {
style: Style::Long,
in_type: Type::Conjunction,
},
expected: "Раја, Гаја и Влаја",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "sr-RS",
array: vec!["Раја", "Гаја", "Влаја"],
opts: listformat::Options {
style: Style::Short,
in_type: Type::Disjunction,
},
expected: "Раја, Гаја или Влаја",
},
#[cfg(feature = "icu_version_67_plus")]
TestCase {
locale: "sr-RS",
array: vec!["Раја", "Гаја", "Влаја"],
opts: listformat::Options {
style: Style::Long,
in_type: Type::Disjunction,
},
expected: "Раја, Гаја или Влаја",
},
];
for test in tests {
let locale =
crate::Locale::FromULoc(uloc::ULoc::try_from(test.locale).expect("locale exists"));
let formatter =
super::Format::try_new(locale, test.opts.clone()).expect("has list format");
let mut result = String::new();
formatter
.format(&test.array, &mut result)
.expect("formatting worked");
assert_eq!(
test.expected, result,
"actual: {}, from: {:?}",
&result, &test
);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ecma402/src/pluralrules.rs | rust_icu_ecma402/src/pluralrules.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implements the traits found in [ecma402_traits::pluralrules].
use ecma402_traits;
use rust_icu_common as common;
use rust_icu_upluralrules as uplr;
use std::fmt;
/// Implements [ecma402_traits::pluralrules::PluralRules] using ICU as the underlying
/// implementing library.
pub struct PluralRules {
// The internal representation of rules.
rep: uplr::UPluralRules,
}
pub(crate) mod internal {
use ecma402_traits::pluralrules::options;
use rust_icu_sys as usys;
// Converts the trait style option type to an equivalent ICU type.
pub fn to_icu_type(style: &options::Type) -> usys::UPluralType {
match style {
options::Type::Ordinal => usys::UPluralType::UPLURAL_TYPE_ORDINAL,
options::Type::Cardinal => usys::UPluralType::UPLURAL_TYPE_CARDINAL,
}
}
}
impl ecma402_traits::pluralrules::PluralRules for PluralRules {
type Error = common::Error;
/// Creates a new [PluralRules].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
///
/// > Note: not yet implemented: the formatting constraints (min integer digits and such).
fn try_new<L>(l: L, opts: ecma402_traits::pluralrules::Options) -> Result<Self, Self::Error>
where
L: ecma402_traits::Locale,
Self: Sized,
{
let locale = format!("{}", l);
let style_type = internal::to_icu_type(&opts.in_type);
let rep = uplr::UPluralRules::try_new_styled(&locale, style_type)?;
Ok(PluralRules { rep })
}
/// Formats the plural class of `number` into the supplied `writer`.
///
/// The function implements [`Intl.PluralRules`][plr] from [ECMA 402][ecma].
///
/// [plr]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn select<W>(&self, number: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write,
{
let result = self.rep.select(number).map_err(|e| e.into())?;
write!(writer, "{}", result)
}
}
#[cfg(test)]
mod testing {
use super::*;
use ecma402_traits::pluralrules;
use ecma402_traits::pluralrules::PluralRules;
use rust_icu_uloc as uloc;
use std::convert::TryFrom;
#[test]
fn plurals_per_locale() -> Result<(), common::Error> {
#[derive(Debug, Clone)]
struct TestCase {
locale: &'static str,
opts: pluralrules::Options,
numbers: Vec<f64>,
expected: Vec<&'static str>,
}
let tests = vec![
TestCase {
locale: "ar_EG",
opts: Default::default(),
numbers: vec![0 as f64, 1 as f64, 2 as f64, 6 as f64, 18 as f64],
expected: vec!["zero", "one", "two", "few", "many"],
},
TestCase {
locale: "ar_EG",
opts: pluralrules::Options {
in_type: pluralrules::options::Type::Ordinal,
..Default::default()
},
numbers: vec![0 as f64, 1 as f64, 2 as f64, 6 as f64, 18 as f64],
expected: vec!["other", "other", "other", "other", "other"],
},
TestCase {
locale: "sr_RS",
opts: Default::default(),
numbers: vec![0 as f64, 1 as f64, 2 as f64, 4 as f64, 6 as f64, 18 as f64],
expected: vec!["other", "one", "few", "few", "other", "other"],
},
TestCase {
locale: "sr_RS",
opts: pluralrules::Options {
in_type: pluralrules::options::Type::Ordinal,
..Default::default()
},
numbers: vec![0 as f64, 1 as f64, 2 as f64, 4 as f64, 6 as f64, 18 as f64],
expected: vec!["other", "other", "other", "other", "other", "other"],
},
];
for test in tests {
let locale =
crate::Locale::FromULoc(uloc::ULoc::try_from(test.locale).expect("locale exists"));
let plr = super::PluralRules::try_new(locale, test.clone().opts)?;
let actual = test
.numbers
.iter()
.map(|n| {
let mut result = String::new();
plr.select(*n, &mut result).unwrap();
result
})
.collect::<Vec<String>>();
assert_eq!(test.expected, actual, "for test case: {:?}", &test);
}
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ecma402/src/datetimeformat.rs | rust_icu_ecma402/src/datetimeformat.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Implements the traits found in [ecma402_traits::datetimeformat].
use ecma402_traits;
use rust_icu_common as common;
use rust_icu_udat as udat;
use rust_icu_uloc as uloc;
use rust_icu_ustring as ustring;
use std::{convert::TryFrom, fmt};
#[derive(Debug)]
pub struct DateTimeFormat {
// The internal representation of date-time formatting.
rep: udat::UDateFormat,
}
pub(crate) mod internal {
use ecma402_traits::datetimeformat::DateTimeFormatOptions;
use ecma402_traits::datetimeformat::options;
use rust_icu_common as common;
use rust_icu_ustring as ustring;
use rust_icu_uloc as uloc;
use std::convert::TryFrom;
use anyhow::anyhow;
fn check_auto_styling_set(opts: &DateTimeFormatOptions) -> Result<(), common::Error> {
if opts.date_style.is_some() || opts.time_style.is_some() {
return Err(common::Error::Wrapper(
anyhow!("can't use custom styling because date_style or time_style is set")));
}
Ok(())
}
/// The skeleton pattern components come from:
/// <https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetimepatterngenerator>
pub fn skeleton_from_opts(opts: &DateTimeFormatOptions) -> Result<ustring::UChar, common::Error> {
let mut skel = vec![];
// Looks like date and time style are mutually exclusive with other
// settings.
if let Some(ref date_style) = &opts.date_style {
match date_style {
options::Style::Full => {}
options::Style::Long => {}
options::Style::Medium => {}
options::Style::Short => {}
}
}
if let Some(ref time_style) = &opts.time_style {
match time_style {
options::Style::Full => {}
options::Style::Long => {}
options::Style::Medium => {}
options::Style::Short => {}
}
}
if let Some(ref digits) = &opts.fractional_second_digits {
check_auto_styling_set(opts)?;
match digits.get() {
1 => skel.push("S"),
2 => skel.push("SS"),
3 => skel.push("SSS"),
_ => skel.push("SSSS"),
}
}
if let Some(ref day_period) = &opts.day_period {
check_auto_styling_set(opts)?;
match day_period {
options::DayPeriod::Short => skel.push("a"),
// Not obvious for other match arms.
options::DayPeriod::Long => {},
options::DayPeriod::Narrow => {}
}
}
if let Some(ref weekday) = &opts.weekday {
check_auto_styling_set(opts)?;
match weekday {
options::Weekday::Long => skel.push("EEEE"),
options::Weekday::Short => skel.push("EEE"),
options::Weekday::Narrow => skel.push("EEEEEE"),
}
}
if let Some(ref era) = &opts.era {
check_auto_styling_set(opts)?;
match era {
options::Era::Long => skel.push("GGGG"),
options::Era::Short => skel.push("GG"),
options::Era::Narrow => skel.push("GGGGG"),
}
}
if let Some(ref year) =&opts.year {
check_auto_styling_set(opts)?;
match year {
options::DisplaySize::Numeric => skel.push("yyyy"),
options::DisplaySize::TwoDigit => skel.push("yy"),
}
}
if let Some(ref month) = &opts.month {
check_auto_styling_set(opts)?;
match month {
options::Month::Numeric => skel.push("M"),
options::Month::TwoDigit => skel.push("MM"),
options::Month::Short => skel.push("MMM"),
options::Month::Long => skel.push("MMMM"),
options::Month::Narrow => skel.push("MMMMM"),
}
}
if let Some(day) = &opts.day {
check_auto_styling_set(opts)?;
match day {
options::DisplaySize::Numeric => skel.push("d"),
options::DisplaySize::TwoDigit => skel.push("dd"),
}
}
if let Some(hour) = &opts.hour {
check_auto_styling_set(opts)?;
if let Some(hour_cycle) = &opts.hour_cycle {
match hour_cycle {
options::HourCycle::H11 =>
match hour {
options::DisplaySize::Numeric => skel.push("K"),
options::DisplaySize::TwoDigit => skel.push("KK"),
},
options::HourCycle::H12 =>
match hour {
options::DisplaySize::Numeric => skel.push("h"),
options::DisplaySize::TwoDigit => skel.push("hh"),
},
options::HourCycle::H23 =>
match hour {
options::DisplaySize::Numeric => skel.push("H"),
options::DisplaySize::TwoDigit => skel.push("HH"),
},
options::HourCycle::H24 => match hour {
options::DisplaySize::Numeric => skel.push("k"),
options::DisplaySize::TwoDigit => skel.push("kk"),
}
}
} else {
// This may not be correct for 23/24 hours locale default.
match hour {
options::DisplaySize::Numeric => skel.push("h"),
options::DisplaySize::TwoDigit => skel.push("hh"),
}
}
}
if let Some(minute) = &opts.minute {
check_auto_styling_set(opts)?;
match minute {
options::DisplaySize::Numeric => skel.push("m"),
options::DisplaySize::TwoDigit => skel.push("mm"),
}
}
if let Some(second) = &opts.second {
check_auto_styling_set(opts)?;
match second {
options::DisplaySize::Numeric => skel.push("s"),
options::DisplaySize::TwoDigit => skel.push("ss"),
}
}
if let Some(time_zone_style) = &opts.time_zone_style {
check_auto_styling_set(opts)?;
match time_zone_style {
options::TimeZoneStyle::Long => skel.push("zzzz"),
options::TimeZoneStyle::Short => skel.push("O"),
}
}
let concat: String = skel.join(" ");
ustring::UChar::try_from(&concat[..])
}
// Modifies the input locale based on the input pattern. The settings here can only
// be set on the locale used for formatting, not on the date time formatting pattern.
//
// Note: this only works with the BCP47 timezones ("uslax", not "America/Los_Angeles").
pub fn locale_from_opts(locale: uloc::ULoc, opts: &DateTimeFormatOptions) -> uloc::ULoc {
let mut locale = uloc::ULocMut::from(locale);
if let Some(calendar) = &opts.calendar {
locale.set_unicode_keyvalue("ca", &calendar.0);
}
if let Some(n) = &opts.numbering_system {
locale.set_unicode_keyvalue("nu", &n.0);
}
if let Some(tz) = &opts.time_zone {
locale.set_unicode_keyvalue("tz", &tz.0);
}
if let Some(h) = &opts.hour_cycle {
locale.set_unicode_keyvalue("hc", &format!("{}", h));
}
// This will panic if any of the settings above are invalid.
let loc = uloc::ULoc::from(locale);
loc
}
}
impl ecma402_traits::datetimeformat::DateTimeFormat for DateTimeFormat {
type Error = common::Error;
/// Creates a new [DateTimeFormat].
///
/// Creation may fail, for example, if the locale-specific data is not loaded,
/// or if the supplied options are inconsistent.
fn try_new<L>(
l: L,
opts: ecma402_traits::datetimeformat::DateTimeFormatOptions,
) -> Result<Self, Self::Error>
where
L: ecma402_traits::Locale,
Self: Sized,
{
let locale = internal::locale_from_opts(
uloc::ULoc::try_from(&format!("{}", l)[..])?, &opts);
let gen = udat::UDatePatternGenerator::new(&locale)?;
let pattern = gen.get_best_pattern_ustring(
&internal::skeleton_from_opts(&opts)?)?;
// The correct timezone ID comes from the resulting locale.
let tz_id = locale.keyword_value("timezone")?.or(Some("".to_owned())).unwrap();
let tz_id = ustring::UChar::try_from(&tz_id[..])?;
let rep = udat::UDateFormat::new_with_pattern(&locale, &tz_id, &pattern)?;
Ok(DateTimeFormat { rep })
}
/// Formats `date` into the supplied `writer`.
///
/// The function implements [`Intl.DateTimeFormat`][link1] from [ECMA 402][ecma]. The `date`
/// is expressed in possibly fractional seconds since the Unix Epoch. The formatting time zone
/// and calendar are taken from the locale that was passed into `DateTimeFormat::try_new`.
///
/// [link1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn format<W>(&self, date: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write,
{
let result = self.rep.format(date).map_err(|e| e.into())?;
write!(writer, "{}", result)
}
}
#[cfg(test)]
mod testing {
use ecma402_traits::datetimeformat::{options, DateTimeFormat, DateTimeFormatOptions, };
use regex::Regex;
use rust_icu_sys as usys;
use rust_icu_uloc as uloc;
use std::convert::TryFrom;
use super::*;
#[test]
fn date_time_format_examples() -> Result<(), common::Error> {
#[derive(Debug, Clone)]
struct TestCase {
locale: &'static str,
opts: DateTimeFormatOptions,
dates: Vec<usys::UDate>,
expected_regex: Vec<&'static str>,
}
let tests = vec![
TestCase {
locale: "sr-RS",
opts: DateTimeFormatOptions{
year: Some(options::DisplaySize::Numeric),
// If time_zone is unset, this becomes a conversion into the
// "local" time zone, which may make this test brittle.
time_zone: Some("UTC".into()),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec!["1970."],
},
// In ICU 63 this gets reported as "GMT-08:00", likely the ICU data
// from then didn't contain the Serbian long spellout of the "uslax"
// time zone. Turning on from 67 onwards, since at the time this
// test was written that was the oldest version that did have the
// long spellout.
#[cfg(feature="icu_version_67_plus")]
TestCase {
locale: "sr",
opts: DateTimeFormatOptions{
time_zone: Some(options::TimeZone("uslax".to_owned())),
time_zone_style: Some(options::TimeZoneStyle::Long),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec!["Северноамеричко пацифичко стандардно време"],
},
TestCase {
locale: "en-US",
opts: DateTimeFormatOptions{
time_zone: Some(options::TimeZone("uslax".to_owned())),
weekday: Some(options::Weekday::Long),
year: Some(options::DisplaySize::Numeric),
day: Some(options::DisplaySize::Numeric,),
month: Some(options::Month::Short),
hour: Some(options::DisplaySize::Numeric),
minute: Some(options::DisplaySize::Numeric),
second: Some(options::DisplaySize::Numeric),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec!["Wednesday, Dec 31, 1969, 4:00:10.PM"],
},
TestCase {
locale: "en-US",
opts: DateTimeFormatOptions{
time_zone: Some(options::TimeZone("uslax".to_owned())),
weekday: Some(options::Weekday::Long),
year: Some(options::DisplaySize::Numeric),
day: Some(options::DisplaySize::Numeric,),
month: Some(options::Month::Short),
hour: Some(options::DisplaySize::Numeric),
minute: Some(options::DisplaySize::Numeric),
second: Some(options::DisplaySize::Numeric),
time_zone_style: Some(options::TimeZoneStyle::Short),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec![r"Wednesday, Dec 31, 1969, 4:00:10.PM.GMT\-8"],
},
TestCase {
locale: "en-US",
opts: DateTimeFormatOptions{
time_zone: Some(options::TimeZone("nlams".to_owned())),
weekday: Some(options::Weekday::Long),
year: Some(options::DisplaySize::Numeric),
day: Some(options::DisplaySize::Numeric,),
month: Some(options::Month::Short),
hour: Some(options::DisplaySize::Numeric),
minute: Some(options::DisplaySize::Numeric),
second: Some(options::DisplaySize::Numeric),
time_zone_style: Some(options::TimeZoneStyle::Short),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec![r"Thursday, Jan 1, 1970, 1:00:10.AM.GMT\+1"],
},
TestCase {
locale: "en-US",
opts: DateTimeFormatOptions{
time_zone: Some(options::TimeZone("rumow".to_owned())),
weekday: Some(options::Weekday::Long),
year: Some(options::DisplaySize::Numeric),
day: Some(options::DisplaySize::Numeric,),
month: Some(options::Month::Short),
hour: Some(options::DisplaySize::Numeric),
minute: Some(options::DisplaySize::Numeric),
second: Some(options::DisplaySize::Numeric),
time_zone_style: Some(options::TimeZoneStyle::Short),
..Default::default()
},
dates: vec![10000_f64],
expected_regex: vec![r"Thursday, Jan 1, 1970, 3:00:10.AM.GMT\+3"],
},
];
for test in tests {
let locale =
crate::Locale::FromULoc(uloc::ULoc::try_from(test.locale).expect("locale exists"));
let formatter = super::DateTimeFormat::try_new(locale, test.clone().opts)?;
let actual: Vec<String> = test
.dates
.iter()
.map(|d| {
let mut result = String::new();
formatter
.format(*d, &mut result)
.expect(&format!("can format: {}", d));
result
})
.collect();
let actual = test.expected_regex.clone().iter().zip(actual)
.map(|(x, a)|
(Regex::new(x).unwrap().is_match(&a), a)
).collect::<Vec<_>>();
let result = actual.iter().map(|p| p.0).all(|x| x);
assert!(result, "for test case: {:?}\n\tactual: {:?}\n\texpected: {:?}",
&test, &actual, &test.expected_regex);
}
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_umsg/src/lib.rs | rust_icu_umsg/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Locale-aware message formatting.
//!
//! Implementation of the text formatting code from the ICU4C
//! [`umsg.h`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/umsg_8h.html) header.
//! Skip to the section ["Example use"](#example-use) below if you want to see it in action.
//!
//! The library inherits all pattern and formatting specifics from the corresponding [ICU C++
//! API](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classicu_1_1MessageFormat.html).
//!
//! This is the support for [MessageFormat](http://userguide.icu-project.org/formatparse/messages)
//! message formatting. The `MessageFormat` uses ICU data to format text properly based on the
//! locale selected at formatter initialization. This includes formatting dates, times,
//! currencies, and other text.
//!
//! > **Note:** The `MessageFormat` library does not handle loading the format patterns in the
//! > appropriate language. This task is left to the application author.
//!
//! # Example use
//!
//! The example below shows how to format values into an English text. For more detail about
//! formatting specifics see [message_format!].
//!
//! ```ignore
//! use rust_icu_sys as sys;
//! use rust_icu_common as common;
//! use rust_icu_ustring as ustring;
//! use rust_icu_uloc as uloc;
//! use rust_icu_umsg::{self as umsg, message_format};
//! # use rust_icu_ucal as ucal;
//! # use std::convert::TryFrom;
//! #
//! # struct TzSave(String);
//! # impl Drop for TzSave {
//! # fn drop(&mut self) {
//! # ucal::set_default_time_zone(&self.0);
//! # }
//! # }
//!
//! fn testfn() -> Result<(), common::Error> {
//! # let _ = TzSave(ucal::get_default_time_zone()?);
//! # ucal::set_default_time_zone("Europe/Amsterdam")?;
//! let loc = uloc::ULoc::try_from("en-US-u-tz-uslax")?;
//! let msg = ustring::UChar::try_from(
//! r"Formatted double: {0,number,##.#},
//! Formatted integer: {1,number,integer},
//! Formatted string: {2},
//! Date: {3,date,full}",
//! )?;
//!
//! let fmt = umsg::UMessageFormat::try_from(&msg, &loc)?;
//! let hello = ustring::UChar::try_from("Hello! Добар дан!")?;
//! let result = umsg::message_format!(
//! fmt,
//! { 43.4 => Double },
//! { 31337 => Integer },
//! { hello => String },
//! { 0.0 => Date },
//! )?;
//!
//! assert_eq!(
//! r"Formatted double: 43.4,
//! Formatted integer: 31,337,
//! Formatted string: Hello! Добар дан!,
//! Date: Thursday, January 1, 1970",
//! result
//! );
//! Ok(())
//! }
//! # fn main() -> Result<(), common::Error> {
//! # testfn()
//! # }
//! ```
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::*, rust_icu_uloc as uloc,
rust_icu_ustring as ustring, std::convert::TryFrom,
};
use sealed::Sealed;
#[doc(hidden)]
pub use {rust_icu_sys as __sys, rust_icu_ustring as __ustring, std as __std};
/// The implementation of the ICU `UMessageFormat*`.
///
/// Use the [UMessageFormat::try_from] to create a message formatter for a given message pattern in
/// the [Messageformat](http://userguide.icu-project.org/formatparse/messages) and a specified
/// locale. Use the macro [message_format!] to actually format the arguments.
///
/// [UMessageFormat] supports very few methods when compared to the wealth of functions that one
/// can see in
/// [`umsg.h`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/umsg_8h.html). It is
/// not clear that other functions available there offer significantly more functionality than is
/// given here.
///
/// If, however, you find that the set of methods implemented at the moment are not adequate, feel
/// free to provide a [pull request](https://github.com/google/rust_icu/pulls) implementing what
/// you need.
///
/// Implements `UMessageFormat`.
#[derive(Debug)]
pub struct UMessageFormat {
rep: std::rc::Rc<Rep>,
}
// An internal representation of the message formatter, used to allow cloning.
#[derive(Debug)]
struct Rep {
rep: *mut sys::UMessageFormat,
}
impl Drop for Rep {
/// Drops the content of [sys::UMessageFormat] and releases its memory.
///
/// Implements `umsg_close`.
fn drop(&mut self) {
unsafe {
versioned_function!(umsg_close)(self.rep);
}
}
}
impl Clone for UMessageFormat {
/// Implements `umsg_clone`.
fn clone(&self) -> Self {
// Note this is not OK if UMessageFormat ever grows mutable methods.
UMessageFormat {
rep: self.rep.clone(),
}
}
}
impl UMessageFormat {
/// Creates a new message formatter.
///
/// A single message formatter is created per each pattern-locale combination. Mutable methods
/// from [`umsg`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/umsg_8h.html)
/// are not implemented, and for now requires that all formatting be separate.
///
/// Implements `umsg_open`.
pub fn try_from(
pattern: &ustring::UChar,
locale: &uloc::ULoc,
) -> Result<UMessageFormat, common::Error> {
let pstr = pattern.as_c_ptr();
let loc = locale.as_c_str();
let mut status = common::Error::OK_CODE;
let mut parse_status = common::NO_PARSE_ERROR;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(umsg_open)(
pstr,
pattern.len() as i32,
loc.as_ptr(),
&mut parse_status,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
common::parse_ok(parse_status)?;
Ok(UMessageFormat {
rep: std::rc::Rc::new(Rep { rep }),
})
}
}
/// Given a formatter, formats the passed arguments into the formatter's message.
///
/// The general usage pattern for the formatter is as follows, assuming that `formatter`
/// is an appropriately initialized [UMessageFormat]:
///
/// ``` ignore
/// use rust_icu_umsg as umsg;
/// // let result = umsg::message_format!(
/// // formatter, [{ value => <type_assertion> }, ...]);
/// let result = umsg::message_format!(formatter, { 31337 => Double });
/// ```
///
/// Each fragment `{ value => <type_assertion> }` represents a single positional parameter binding
/// for the pattern in `formatter`. The first fragment corresponds to the positional parameter `0`
/// (which, if an integer, would be referred to as `{0,number,integer}` in a MessageFormat
/// pattern). Since the original C API that this rust library is generated for uses variadic
/// functions for parameter passing, it is very important that the programmer matches the actual
/// parameter types to the types that are expected in the pattern.
///
/// > **Note:** If the types of parameter bindings do not match the expectations in the pattern,
/// > memory corruption may occur, so tread lightly here.
///
/// In general this is very brittle, and an API in a more modern lanugage, or a contemporary C++
/// flavor would probably take a different route were the library to be written today. The rust
/// binding tries to make the API use a bit more palatable by requiring that the programmer
/// explicitly specifies a type for each of the parameters to be passed into the formatter.
///
/// The supported types are not those of a full rust system, but rather a very restricted subset
/// of types that MessageFormat supports:
///
/// | Type | Rust Type | Notes |
/// | ---- | --------- | ----------- |
/// | Double | `f64` | Any numeric parameter not specifically designated as different type, is always a double. See section below on Doubles. |
/// | String | [rust_icu_ustring::UChar] | |
/// | Integer | `i32` | |
/// | Date | [rust_icu_sys::UDate] (alias for `f64`) | Is used to format dates. Depending on the date format requested in the pattern used in [UMessageFormat], the end result of date formatting could be one of a wide variety of [date formats](http://userguide.icu-project.org/formatparse/datetime).|
///
/// ## Double as numeric parameter
///
/// According to the [ICU documentation for
/// `umsg_format`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/umsg_8h.html#a90a4b5fe778754e5da52f7c2e5fd6048):
///
/// > for all numeric arguments double is assumed unless the type is explicitly
/// > integer (long). All choice format arguments must be of type double.
///
/// ## Strings
///
/// We determined by code inspection that the string format must be `rust_icu_ustring::UChar`.
///
/// # Example use
///
/// ```
/// use rust_icu_sys as sys;
/// use rust_icu_common as common;
/// use rust_icu_ustring as ustring;
/// use rust_icu_uloc as uloc;
/// use rust_icu_umsg::{self as umsg, message_format};
/// # use rust_icu_ucal as ucal;
/// # use std::convert::TryFrom;
/// #
/// # struct TzSave(String);
/// # impl Drop for TzSave {
/// # // Restore the system time zone upon exit.
/// # fn drop(&mut self) {
/// # ucal::set_default_time_zone(&self.0);
/// # }
/// # }
///
/// fn testfn() -> Result<(), common::Error> {
/// # let _ = TzSave(ucal::get_default_time_zone()?);
/// # ucal::set_default_time_zone("Europe/Amsterdam")?;
/// let loc = uloc::ULoc::try_from("en-US")?;
/// let msg = ustring::UChar::try_from(
/// r"Formatted double: {0,number,##.#},
/// Formatted integer: {1,number,integer},
/// Formatted string: {2},
/// Date: {3,date,full}",
/// )?;
///
/// let fmt = umsg::UMessageFormat::try_from(&msg, &loc)?;
/// let hello = ustring::UChar::try_from("Hello! Добар дан!")?;
/// let result = umsg::message_format!(
/// fmt,
/// { 43.4 => Double },
/// { 31337 => Integer },
/// { hello => String },
/// { 0.0 => Date },
/// )?;
///
/// assert_eq!(
/// r"Formatted double: 43.4,
/// Formatted integer: 31,337,
/// Formatted string: Hello! Добар дан!,
/// Date: Thursday, January 1, 1970",
/// result
/// );
/// Ok(())
/// }
/// # fn main() -> Result<(), common::Error> {
/// # testfn()
/// # }
/// ```
///
/// Implements `umsg_format`.
/// Implements `umsg_vformat`.
#[macro_export]
macro_rules! message_format {
($dest:expr $(,)?) => {
$crate::__std::compile_error!("you should not format a message without parameters")
};
($dest:expr, $( {$arg:expr => $t:ident} ),+ $(,)?) => {
unsafe {
$crate::format_args(&$dest, ($($crate::checkarg!($arg, $t),)*))
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! checkarg {
($e:expr, Double) => {{
let x: $crate::__std::primitive::f64 = $e;
x
}};
($e:expr, String) => {{
let x: $crate::__ustring::UChar = $e;
x
}};
($e:expr, Integer) => {{
let x: $crate::__std::primitive::i32 = $e;
x
}};
($e:expr, Long) => {{
let x: $crate::__std::primitive::i64 = $e;
x
}};
($e:expr, Date) => {{
let x: $crate::__sys::UDate = $e;
x
}};
}
#[doc(hidden)]
pub unsafe fn format_args(
fmt: &UMessageFormat,
args: impl FormatArgs,
) -> Result<String, common::Error> {
const CAP: usize = 1024;
let mut status = common::Error::OK_CODE;
let mut result = ustring::UChar::new_with_capacity(CAP);
let total_size =
args.format(fmt.rep.rep, result.as_mut_c_ptr(), CAP as i32, &mut status) as usize;
common::Error::ok_or_warning(status)?;
result.resize(total_size);
if total_size > CAP {
args.format(
fmt.rep.rep,
result.as_mut_c_ptr(),
total_size as i32,
&mut status,
);
common::Error::ok_or_warning(status)?;
}
String::try_from(&result)
}
mod sealed {
pub trait Sealed {}
}
/// Traits for types that can be passed to the umsg_format variadic function.
#[doc(hidden)]
pub trait FormatArg: Sealed {
type Raw;
fn to_raw(&self) -> Self::Raw;
}
impl Sealed for f64 {}
impl FormatArg for f64 {
type Raw = f64;
fn to_raw(&self) -> Self::Raw {
*self
}
}
impl Sealed for ustring::UChar {}
impl FormatArg for ustring::UChar {
type Raw = *const UChar;
fn to_raw(&self) -> Self::Raw {
self.as_c_ptr()
}
}
impl Sealed for i32 {}
impl FormatArg for i32 {
type Raw = i32;
fn to_raw(&self) -> Self::Raw {
*self
}
}
impl Sealed for i64 {}
impl FormatArg for i64 {
type Raw = i64;
fn to_raw(&self) -> Self::Raw {
*self
}
}
/// Trait for tuples of elements implementing `FormatArg`.
#[doc(hidden)]
pub trait FormatArgs: Sealed {
#[doc(hidden)]
unsafe fn format(
&self,
fmt: *const sys::UMessageFormat,
result: *mut UChar,
result_length: i32,
status: *mut UErrorCode,
) -> i32;
}
macro_rules! impl_format_args_for_tuples {
($(($($param:ident),*),)*) => {
$(
impl<$($param: FormatArg,)*> Sealed for ($($param,)*) {}
impl<$($param: FormatArg,)*> FormatArgs for ($($param,)*) {
unsafe fn format(
&self,
fmt: *const sys::UMessageFormat,
result: *mut UChar,
result_length: i32,
status: *mut UErrorCode,
) -> i32 {
#[allow(non_snake_case)]
let ($($param,)*) = self;
$(
#[allow(non_snake_case)]
let $param = $crate::FormatArg::to_raw($param);
)*
versioned_function!(umsg_format)(
fmt,
result,
result_length,
status,
$($param,)*
)
}
}
)*
}
}
impl_format_args_for_tuples! {
(A),
(A, B),
(A, B, C),
(A, B, C, D),
(A, B, C, D, E),
(A, B, C, D, E, F),
(A, B, C, D, E, F, G),
(A, B, C, D, E, F, G, H),
(A, B, C, D, E, F, G, H, I),
(A, B, C, D, E, F, G, H, I, J),
(A, B, C, D, E, F, G, H, I, J, K),
(A, B, C, D, E, F, G, H, I, J, K, L),
(A, B, C, D, E, F, G, H, I, J, K, L, M),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y),
(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z),
}
#[cfg(test)]
mod tests {
use super::*;
use rust_icu_ucal as ucal;
struct TzSave(String);
impl Drop for TzSave {
// Restore the system time zone upon exit.
fn drop(&mut self) {
ucal::set_default_time_zone(&self.0).expect("timezone set success");
}
}
#[test]
fn tzsave() -> Result<(), common::Error> {
let _ = TzSave(ucal::get_default_time_zone()?);
ucal::set_default_time_zone("Europe/Amsterdam")?;
Ok(())
}
#[test]
fn basic() -> Result<(), common::Error> {
let _ = TzSave(ucal::get_default_time_zone()?);
ucal::set_default_time_zone("Europe/Amsterdam")?;
let loc = uloc::ULoc::try_from("en-US")?;
let msg = ustring::UChar::try_from(
r"Formatted double: {0,number,##.#},
Formatted integer: {1,number,integer},
Formatted string: {2},
Date: {3,date,full}",
)?;
let fmt = crate::UMessageFormat::try_from(&msg, &loc)?;
let hello = ustring::UChar::try_from("Hello! Добар дан!")?;
let value: i32 = 31337;
let result = message_format!(
fmt,
{ 43.4 => Double },
{ value => Integer },
{ hello => String },
{ 0.0 => Date }
)?;
assert_eq!(
r"Formatted double: 43.4,
Formatted integer: 31,337,
Formatted string: Hello! Добар дан!,
Date: Thursday, January 1, 1970",
result
);
Ok(())
}
#[test]
fn clone() -> Result<(), common::Error> {
let loc = uloc::ULoc::try_from("en-US-u-tz-uslax")?;
let msg = ustring::UChar::try_from(r"Formatted double: {0,number,##.#}")?;
let fmt = crate::UMessageFormat::try_from(&msg, &loc)?;
#[allow(clippy::redundant_clone)]
let result = message_format!(fmt.clone(), { 43.43 => Double })?;
assert_eq!(r"Formatted double: 43.4", result);
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ucol/src/lib.rs | rust_icu_ucol/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU collation support for rust
//!
//! This crate provides [collation](https://en.wikipedia.org/wiki/Unicode_collation_algorithm)
//! (locale-sensitive string ordering), based on the collation as implemented by the ICU library.
//! Specifically the functionality exposed through its C API, as available in the [header
//! `ucol.h`](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ucol_8h.html).
//!
//! The main type is [UCollator], which can be created using `UCollator::try_from` from a `&str`.
//!
//! A detailed discussion of collation is out of scope of source code documentation. An interested
//! reader can check out the [collation documentation on the ICU user
//! guide](http://userguide.icu-project.org/collation).
//!
//! > Are you missing some features from this crate? Consider [reporting an
//! issue](https://github.com/google/rust_icu/issues) or even [contributing the
//! functionality](https://github.com/google/rust_icu/pulls).
//!
//! ## Examples
//!
//! Some example code for the use of collation is given below.
//!
//! First off, the more low-level API, which uses [ustring::UChar] is the following, which requires
//! a conversion to [ustring::UChar] prior to use. This function is mostly used in algorithms that
//! compose Unicode functionality.
//!
//! ```
//! use rust_icu_ustring as ustring;
//! use rust_icu_ucol as ucol;
//! use std::convert::TryFrom;
//! let collator = ucol::UCollator::try_from("sr-Latn").expect("collator");
//! let mut mixed_up = vec!["d", "dž", "đ", "a", "b", "c", "č", "ć"];
//! mixed_up.sort_by(|a, b| {
//! let first = ustring::UChar::try_from(*a).expect("first");
//! let second = ustring::UChar::try_from(*b).expect("second");
//! collator.strcoll(&first, &second)
//! });
//! let alphabet = vec!["a", "b", "c", "č", "ć", "d", "dž", "đ"];
//! assert_eq!(alphabet, mixed_up);
//! ```
//! A more rustful API is [UCollator::strcoll_utf8] which can operate on rust `AsRef<str>` and can
//! be used without converting the input data ahead of time.
//!
//! ```
//! use rust_icu_ustring as ustring;
//! use rust_icu_ucol as ucol;
//! use std::convert::TryFrom;
//! let collator = ucol::UCollator::try_from("sr-Latn").expect("collator");
//! let mut mixed_up = vec!["d", "dž", "đ", "a", "b", "c", "č", "ć"];
//! mixed_up.sort_by(|a, b| collator.strcoll_utf8(a, b).expect("strcoll_utf8"));
//! let alphabet = vec!["a", "b", "c", "č", "ć", "d", "dž", "đ"];
//! assert_eq!(alphabet, mixed_up);
//! ```
use {
rust_icu_common as common,
rust_icu_common::generalized_fallible_getter,
rust_icu_common::generalized_fallible_setter,
rust_icu_common::simple_drop_impl,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_uenum as uenum, rust_icu_ustring as ustring,
std::{cmp::Ordering, convert::TryFrom, ffi, ptr},
};
#[derive(Debug)]
pub struct UCollator {
rep: ptr::NonNull<sys::UCollator>,
}
// Implements `ucol_close`
simple_drop_impl!(UCollator, ucol_close);
impl TryFrom<&str> for UCollator {
type Error = common::Error;
/// Makes a new collator from the supplied locale, e.g. `en-US`, or
/// `de@collation=phonebook`.
///
/// Other examples:
///
/// * `el-u-kf-upper`
/// * `el@colCaseFirst=upper`
///
/// Implements ucol_open
fn try_from(locale: &str) -> Result<UCollator, Self::Error> {
let locale_cstr = ffi::CString::new(locale)?;
let mut status = common::Error::OK_CODE;
// Unsafety note: this is the way to create the collator. We expect all
// the passed-in values to be well-formed.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucol_open)(locale_cstr.as_ptr(), &mut status) as *mut sys::UCollator
};
common::Error::ok_or_warning(status)?;
Ok(UCollator {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
}
impl UCollator {
/// Compares strings `first` and `second` according to the collation rules in this collator.
///
/// Returns [Ordering::Less] if `first` compares as less than `second`, and for other return
/// codes respectively.
///
/// Implements `ucol_strcoll`
pub fn strcoll(&self, first: &ustring::UChar, second: &ustring::UChar) -> Ordering {
let result = unsafe {
assert!(first.len() <= std::i32::MAX as usize);
assert!(second.len() <= std::i32::MAX as usize);
versioned_function!(ucol_strcoll)(
self.rep.as_ptr(),
first.as_c_ptr(),
first.len() as i32,
second.as_c_ptr(),
second.len() as i32,
)
};
UCollator::to_rust_ordering(result)
}
/// Get a sort key for a string from this collator.
///
/// Returns a sort key.
///
/// Implements `ucol_getSortKey`
pub fn get_sort_key(&self, source: &ustring::UChar) -> Vec<u8> {
// Preflight to see how long the buffer should be.
let result_length: i32 = unsafe {
versioned_function!(ucol_getSortKey)(
self.rep.as_ptr(),
source.as_c_ptr(),
source.len() as i32,
std::ptr::null_mut(),
0,
)
};
let mut result: Vec<u8> = vec![0; result_length as usize];
unsafe {
versioned_function!(ucol_getSortKey)(
self.rep.as_ptr(),
source.as_c_ptr(),
source.len() as i32,
result.as_mut_ptr(),
result.len() as i32,
)
};
result
}
/// Compares strings `first` and `second` according to the collation rules in this collator.
///
/// Returns [Ordering::Less] if `first` compares as less than `second`, and for other return
/// codes respectively.
///
/// In contrast to [UCollator::strcoll], this function requires no string conversions to
/// compare two rust strings.
///
/// Implements `ucol_strcoll`
/// Implements `ucol_strcollUTF8`
pub fn strcoll_utf8(
&self,
first: impl AsRef<str>,
second: impl AsRef<str>,
) -> Result<Ordering, common::Error> {
let mut status = common::Error::OK_CODE;
// Unsafety note:
// - AsRef is always well formed UTF-8 in rust.
let result = unsafe {
assert!(first.as_ref().len() <= std::i32::MAX as usize);
assert!(second.as_ref().len() <= std::i32::MAX as usize);
versioned_function!(ucol_strcollUTF8)(
self.rep.as_ptr(),
first.as_ref().as_ptr() as *const ::std::os::raw::c_char,
first.as_ref().len() as i32,
second.as_ref().as_ptr() as *const ::std::os::raw::c_char,
second.as_ref().len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(UCollator::to_rust_ordering(result))
}
// Converts ICU ordering result type to a Rust ordering result type.
fn to_rust_ordering(result: sys::UCollationResult) -> Ordering {
match result {
sys::UCollationResult::UCOL_LESS => Ordering::Less,
sys::UCollationResult::UCOL_GREATER => Ordering::Greater,
sys::UCollationResult::UCOL_EQUAL => Ordering::Equal,
}
}
/// Implements `ucol_getStrength`.
pub fn get_strength(&self) -> sys::UCollationStrength {
let result = unsafe { versioned_function!(ucol_getStrength)(self.rep.as_ptr()) };
result
}
/// Implements `ucol_setStrength`
pub fn set_strength(&mut self, strength: sys::UCollationStrength) {
unsafe { versioned_function!(ucol_setStrength)(self.rep.as_ptr(), strength) };
}
// Implement `ucol_setMaxVariable`
generalized_fallible_setter!(
set_max_variable,
ucol_setMaxVariable,
[max_variable: sys::UColReorderCode,]
);
// Implement `ucol_setAttribute`
generalized_fallible_setter!(
set_attribute,
ucol_setAttribute,
[attr: sys::UColAttribute, value: sys::UColAttributeValue,]
);
// Implement `ucol_getAttribute`
generalized_fallible_getter!(
get_attribute,
ucol_getAttribute,
[attr: sys::UColAttribute,],
sys::UColAttributeValue
);
}
/// Creates an enumeration of all available locales supporting collation.
///
/// Implements `ucol_openAvailableLocales`
/// Implements `ucol_countAvailable`
/// Implements `ucol_getAvailable`
pub fn get_available_locales() -> Result<uenum::Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucol_openAvailableLocales)(&mut status)
};
common::Error::ok_or_warning(status)?;
let result = unsafe { uenum::Enumeration::from_raw_parts(None, rep) };
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let _ = crate::UCollator::try_from("de@collation=phonebook").expect("collator created");
}
#[test]
fn test_available() {
let available = crate::get_available_locales()
.expect("available")
.filter(|e| e.is_ok() /* retain known good */)
.map(|e| e.unwrap() /* known good */)
.collect::<Vec<String>>();
assert_ne!(0, available.iter().count());
}
#[test]
fn strcoll_utf8_test() -> Result<(), common::Error> {
let collator = crate::UCollator::try_from("sr-Latn")?;
let mut mixed_up = vec!["d", "dž", "đ", "a", "b", "c", "č", "ć"];
mixed_up.sort_by(|a, b| collator.strcoll_utf8(a, b).expect("strcoll_utf8"));
let alphabet = vec!["a", "b", "c", "č", "ć", "d", "dž", "đ"];
assert_eq!(alphabet, mixed_up);
Ok(())
}
#[test]
fn strcoll_test() -> Result<(), common::Error> {
let collator = crate::UCollator::try_from("sr-Latn")?;
let mut mixed_up = vec!["d", "dž", "đ", "a", "b", "c", "č", "ć"];
mixed_up.sort_by(|a, b| {
let first = ustring::UChar::try_from(*a).expect("first");
let second = ustring::UChar::try_from(*b).expect("second");
collator.strcoll(&first, &second)
});
let alphabet = vec!["a", "b", "c", "č", "ć", "d", "dž", "đ"];
assert_eq!(alphabet, mixed_up);
Ok(())
}
#[test]
fn get_sort_key_test() -> Result<(), common::Error> {
let collator = crate::UCollator::try_from("sr-Latn")?;
let mut mixed_up = vec!["d", "dž", "đ", "a", "b", "c", "č", "ć"];
mixed_up.sort_by(|a, b| {
let first = ustring::UChar::try_from(*a).expect("first");
let second = ustring::UChar::try_from(*b).expect("second");
let first_key = collator.get_sort_key(&first);
let second_key = collator.get_sort_key(&second);
first_key.cmp(&second_key)
});
let alphabet = vec!["a", "b", "c", "č", "ć", "d", "dž", "đ"];
assert_eq!(alphabet, mixed_up);
Ok(())
}
#[test]
fn attribute_setter() {
let collator = crate::UCollator::try_from("sr-Latn").unwrap();
collator
.set_attribute(
sys::UColAttribute::UCOL_CASE_FIRST,
sys::UColAttributeValue::UCOL_OFF,
)
.unwrap();
let attr = collator
.get_attribute(sys::UColAttribute::UCOL_CASE_FIRST)
.unwrap();
assert_eq!(sys::UColAttributeValue::UCOL_OFF, attr);
collator
.set_attribute(
sys::UColAttribute::UCOL_CASE_FIRST,
sys::UColAttributeValue::UCOL_LOWER_FIRST,
)
.unwrap();
let attr = collator
.get_attribute(sys::UColAttribute::UCOL_CASE_FIRST)
.unwrap();
assert_eq!(sys::UColAttributeValue::UCOL_LOWER_FIRST, attr);
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ustring/src/lib.rs | rust_icu_ustring/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Implementation of the functions in the ICU4C `ustring.h` header.
//!
//! This is where the UTF-8 strings get converted back and forth to the UChar
//! representation.
//!
use {
log::trace, rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::*,
std::convert::TryFrom, std::os::raw,
};
/// The implementation of the ICU `UChar*`.
///
/// While the original type is defined in `umachine.h`, most useful functions for manipulating
/// `UChar*` are in fact here.
///
/// The first thing you probably want to do is to start from a UTF-8 rust string, produce a UChar.
/// This is necessarily done with a conversion. See the `TryFrom` implementations in this crate
/// for that.
///
/// Implements `UChar*` from ICU.
#[derive(Debug, Clone)]
pub struct UChar {
rep: Vec<rust_icu_sys::UChar>,
}
/// Same as `rust_icu_common::buffered_string_method_with_retry`, but for unicode strings.
///
/// Example use:
///
/// Declares an internal function `select_impl` with a templatized type signature, which is then
/// called in subsequent code.
///
/// ```rust ignore
/// pub fn select_ustring(&self, number: f64) -> Result<ustring::UChar, common::Error> {
/// const BUFFER_CAPACITY: usize = 20;
/// buffered_uchar_method_with_retry!(
/// select_impl,
/// BUFFER_CAPACITY,
/// [rep: *const sys::UPluralRules, number: f64,],
/// []
/// );
///
/// select_impl(
/// versioned_function!(uplrules_select),
/// self.rep.as_ptr(),
/// number,
/// )
/// }
/// ```
#[macro_export]
macro_rules! buffered_uchar_method_with_retry {
($method_name:ident, $buffer_capacity:expr,
[$($before_arg:ident: $before_arg_type:ty,)*],
[$($after_arg:ident: $after_arg_type:ty,)*]) => {
fn $method_name(
method_to_call: unsafe extern "C" fn(
$($before_arg_type,)*
*mut sys::UChar,
i32,
$($after_arg_type,)*
*mut sys::UErrorCode,
) -> i32,
$($before_arg: $before_arg_type,)*
$($after_arg: $after_arg_type,)*
) -> Result<ustring::UChar, common::Error> {
let mut status = common::Error::OK_CODE;
let mut buf: Vec<sys::UChar> = vec![0; $buffer_capacity];
// Requires that any pointers that are passed in are valid.
let full_len: i32 = unsafe {
assert!(common::Error::is_ok(status), "status: {:?}", status);
method_to_call(
$($before_arg,)*
buf.as_mut_ptr() as *mut sys::UChar,
$buffer_capacity as i32,
$($after_arg,)*
&mut status,
)
};
// ICU methods are inconsistent in whether they silently truncate the output or treat
// the overflow as an error, so we need to check both cases.
if status == sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR ||
(common::Error::is_ok(status) &&
full_len > $buffer_capacity
.try_into()
.map_err(|e| common::Error::wrapper(e))?) {
status = common::Error::OK_CODE;
assert!(full_len > 0);
let full_len: usize = full_len
.try_into()
.map_err(|e| common::Error::wrapper(e))?;
buf.resize(full_len, 0);
// Same unsafe requirements as above, plus full_len must be exactly the output
// buffer size.
unsafe {
assert!(common::Error::is_ok(status), "status: {:?}", status);
method_to_call(
$($before_arg,)*
buf.as_mut_ptr() as *mut sys::UChar,
full_len as i32,
$($after_arg,)*
&mut status,
)
};
}
common::Error::ok_or_warning(status)?;
// Adjust the size of the buffer here.
if (full_len >= 0) {
let full_len: usize = full_len
.try_into()
.map_err(|e| common::Error::wrapper(e))?;
buf.resize(full_len, 0);
}
Ok(ustring::UChar::from(buf))
}
}
}
impl TryFrom<&str> for crate::UChar {
type Error = common::Error;
/// Tries to produce a string from the UTF-8 encoded thing.
///
/// This conversion ignores warnings (e.g. warnings about unterminated buffers), since for rust
/// they are not relevant.
///
/// Implements `u_strFromUTF8`.
fn try_from(rust_string: &str) -> Result<Self, Self::Error> {
let mut status = common::Error::OK_CODE;
let mut dest_length: i32 = 0;
// Preflight to see how long the buffer should be. See second call below
// for safety notes.
//
// TODO(fmil): Consider having a try_from variant which allocates a buffer
// of sufficient size instead of running the algorithm twice.
trace!("utf8->UChar*: {}, {:?}", rust_string.len(), rust_string);
// Requires that rust_string be a valid C string.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(u_strFromUTF8)(
std::ptr::null_mut(),
0,
&mut dest_length,
rust_string.as_ptr() as *const raw::c_char,
rust_string.len() as i32,
&mut status,
);
}
trace!("before error check");
// We expect buffer overflow error here. The API is weird, but there you go.
common::Error::ok_preflight(status)?;
trace!("input utf8->UChar*: {:?}", rust_string);
let mut rep: Vec<sys::UChar> = vec![0; dest_length as usize];
let mut status = common::Error::OK_CODE;
// Assumes that rust_string contains a valid rust string. It is OK for the string to have
// embedded zero bytes. Assumes that 'rep' is large enough to hold the entire result.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(u_strFromUTF8)(
rep.as_mut_ptr(),
rep.len() as i32,
&mut dest_length,
rust_string.as_ptr() as *const raw::c_char,
rust_string.len() as i32,
&mut status,
);
}
common::Error::ok_or_warning(status)?;
trace!("result utf8->uchar*[{}]: {:?}", dest_length, rep);
Ok(crate::UChar { rep })
}
}
impl TryFrom<&UChar> for String {
type Error = common::Error;
/// Tries to produce a UTF-8 encoded rust string from a UChar.
///
/// This conversion ignores warnings and only reports actual ICU errors when
/// they happen.
///
/// Implements `u_strToUTF8`.
fn try_from(u: &UChar) -> Result<String, Self::Error> {
let mut status = common::Error::OK_CODE;
let mut dest_length: i32 = 0;
// First probe for required destination length.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(u_strToUTF8)(
std::ptr::null_mut(),
0,
&mut dest_length,
u.rep.as_ptr(),
u.rep.len() as i32,
&mut status,
);
}
trace!("preflight UChar*->utf8 buf[{}]", dest_length);
// The API doesn't really document this well, but the preflight code will report buffer
// overflow error even when we are explicitly just trying to check for the size of the
// resulting buffer.
common::Error::ok_preflight(status)?;
// Buffer to store the converted string.
let mut buf: Vec<u8> = vec![0; dest_length as usize];
trace!("pre: result UChar*->utf8 buf[{}]: {:?}", buf.len(), buf);
let mut status = common::Error::OK_CODE;
// Requires that buf is a buffer with enough capacity to store the
// resulting string.
unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(u_strToUTF8)(
buf.as_mut_ptr() as *mut raw::c_char,
buf.len() as i32,
&mut dest_length,
u.rep.as_ptr(),
u.rep.len() as i32,
&mut status,
);
}
trace!("post: result UChar*->utf8 buf[{}]: {:?}", buf.len(), buf);
common::Error::ok_or_warning(status)?;
let s = String::from_utf8(buf);
match s {
Err(e) => Err(e.into()),
Ok(x) => {
trace!("result UChar*->utf8: {:?}", x);
Ok(x)
}
}
}
}
impl From<Vec<sys::UChar>> for crate::UChar {
/// Adopts a vector of [sys::UChar] into a string.
fn from(rep: Vec<sys::UChar>) -> crate::UChar {
crate::UChar { rep }
}
}
impl crate::UChar {
/// Allocates a new UChar with given capacity.
///
/// Capacity and size must always be the same with `UChar` when used for interacting with
/// low-level code.
pub fn new_with_capacity(capacity: usize) -> crate::UChar {
let rep: Vec<sys::UChar> = vec![0; capacity];
crate::UChar::from(rep)
}
/// Creates a new [crate::UChar] from its low-level representation, a buffer
/// pointer and a buffer size.
///
/// Does *not* take ownership of the buffer that was passed in.
///
/// **DO NOT USE UNLESS YOU HAVE NO OTHER CHOICE.**
///
/// # Safety
///
/// `rep` must point to an initialized sequence of at least `len` `UChar`s.
pub unsafe fn clone_from_raw_parts(rep: *mut sys::UChar, len: i32) -> crate::UChar {
assert!(len >= 0);
// Always works for len: i32 >= 0.
let cap = len as usize;
// View the deconstructed buffer as a vector of UChars. Then make a
// copy of it to return. This is not efficient, but is always safe.
let original = Vec::from_raw_parts(rep, cap, cap);
let copy = original.clone();
// Don't free the buffer we don't own.
std::mem::forget(original);
crate::UChar::from(copy)
}
/// Converts into a zeroed-out string.
///
/// This is a very weird ICU API thing, where there apparently exists a zero-terminated
/// `UChar*`.
pub fn make_z(&mut self) {
self.rep.push(0);
}
/// Returns the constant pointer to the underlying C representation.
/// Intended for use in low-level code.
pub fn as_c_ptr(&self) -> *const rust_icu_sys::UChar {
self.rep.as_ptr()
}
/// Returns the length of the string, in code points.
pub fn len(&self) -> usize {
self.rep.len()
}
/// Returns whether the string is empty.
pub fn is_empty(&self) -> bool {
self.rep.is_empty()
}
/// Returns the underlying representation as a mutable C representation. Caller MUST ensure
/// that the representation won't be reallocated as result of adding anything to it, and that
/// it is correctly sized, or bad things will happen.
pub fn as_mut_c_ptr(&mut self) -> *mut sys::UChar {
self.rep.as_mut_ptr()
}
/// Resizes this string to match new_size.
///
/// If the string is made longer, the new space is filled with zeroes.
pub fn resize(&mut self, new_size: usize) {
self.rep.resize(new_size, 0);
}
/// Returns the equivalent UTF-8 string, useful for debugging.
pub fn as_string_debug(&self) -> String {
String::try_from(self).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip_conversion() {
let samples = vec!["", "Hello world!", "❤ Hello world ❤"];
for s in samples.iter() {
let uchar =
crate::UChar::try_from(*s).expect(&format!("forward conversion succeeds: {}", s));
let res =
String::try_from(&uchar).expect(&format!("back conversion succeeds: {:?}", uchar));
assert_eq!(*s, res);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_uenum/src/lib.rs | rust_icu_uenum/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Rust implementation of the `uenum.h` C API header for ICU.
use {
rust_icu_common as common, rust_icu_sys as sys,
rust_icu_sys::*,
std::{convert::TryFrom, ffi, str},
};
/// Rust wrapper for the UEnumeration iterator.
///
/// Implements `UEnumeration`
#[derive(Debug)]
pub struct Enumeration {
// The raw underlying character array, in case the underlying char array is
// owned by this enumeration.
_raw: Option<common::CStringVec>,
// Internal low-level representation of the enumeration. The internal
// representation relies on `raw` and `len` above and must live at most as
// long.
rep: *mut sys::UEnumeration,
}
impl Enumeration {
/// Internal representation, for ICU4C methods that require it.
pub fn repr(&mut self) -> *mut sys::UEnumeration {
self.rep
}
/// Creates an empty `Enumeration`.
pub fn empty() -> Self {
Enumeration::try_from(&vec![][..]).unwrap()
}
}
impl Default for Enumeration {
fn default() -> Self {
Self::empty()
}
}
/// Creates an enumeration iterator from a vector of UTF-8 strings.
impl TryFrom<&[&str]> for Enumeration {
type Error = common::Error;
/// Constructs an enumeration from a string slice.
///
/// Implements `uenum_openCharStringsEnumeration`
fn try_from(v: &[&str]) -> Result<Enumeration, common::Error> {
let raw = common::CStringVec::new(v)?;
let mut status = common::Error::OK_CODE;
let rep: *mut sys::UEnumeration = unsafe {
versioned_function!(uenum_openCharStringsEnumeration)(
raw.as_c_array(),
raw.len() as i32,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
// rep should not be null without an error set, but:
// https://unicode-org.atlassian.net/browse/ICU-20918
assert!(!rep.is_null());
Ok(Enumeration {
rep,
_raw: Some(raw),
})
}
}
impl Drop for Enumeration {
/// Drops the Enumeration, deallocating its internal representation hopefully correctly.
///
/// Implements `uenum_close`
fn drop(&mut self) {
unsafe { versioned_function!(uenum_close)(self.rep) };
}
}
impl Iterator for Enumeration {
type Item = Result<String, common::Error>;
/// Yields the next element stored in the enumeration.
///
/// Implements `uenum_next`
fn next(&mut self) -> Option<Self::Item> {
let mut len: i32 = 0;
let mut status = common::Error::OK_CODE;
// Requires that self.rep is a valid pointer to a sys::UEnumeration.
assert!(!self.rep.is_null());
let raw = unsafe { versioned_function!(uenum_next)(self.rep, &mut len, &mut status) };
if raw.is_null() {
// No more elements to iterate over.
return None;
}
let result = common::Error::ok_or_warning(status);
match result {
Ok(()) => {
assert!(!raw.is_null());
// Requires that raw is a valid pointer to a C string.
let cstring = unsafe { ffi::CStr::from_ptr(raw) }; // Borrowing
Some(Ok(cstring
.to_str()
.expect("could not convert to string")
.to_string()))
}
Err(e) => Some(Err(e)),
}
}
}
impl Enumeration {
/// Constructs an [Enumeration] from a raw pointer.
///
/// **DO NOT USE THIS FUNCTION UNLESS THERE IS NO OTHER CHOICE!**
///
/// We tried to keep this function hidden to avoid the
/// need to have a such a powerful unsafe function in the
/// public API. It worked up to a point for free functions.
///
/// It no longer works on high-level methods that return
/// enumerations, since then we'd need to depend on them to
/// create an [Enumeration].
#[doc(hidden)]
pub unsafe fn from_raw_parts(
_raw: Option<common::CStringVec>,
rep: *mut sys::UEnumeration,
) -> Enumeration {
Enumeration { _raw, rep }
}
}
#[doc(hidden)]
/// Implements `ucal_openCountryTimeZones`.
// This should be in the `ucal` crate, but not possible because of the raw enum initialization.
// Tested in `ucal`.
pub fn ucal_open_country_time_zones(country: &str) -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz_country = ffi::CString::new(country)?;
// Requires that the asciiz country be a pointer to a valid C string.
let raw_enum = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_openCountryTimeZones)(asciiz_country.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(Enumeration {
_raw: None,
rep: raw_enum,
})
}
#[doc(hidden)]
/// Implements `ucal_openTimeZoneIDEnumeration`
// This should be in the `ucal` crate, but not possible because of the raw enum initialization.
// Tested in `ucal`.
pub fn ucal_open_time_zone_id_enumeration(
zone_type: sys::USystemTimeZoneType,
region: Option<&str>,
raw_offset: Option<i32>,
) -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz_region = match region {
None => None,
Some(region) => Some(ffi::CString::new(region)?),
};
let mut repr_raw_offset: i32 = raw_offset.unwrap_or_default();
// asciiz_region should be a valid asciiz pointer. raw_offset is an encoding
// of an optional value by a C pointer.
let raw_enum = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_openTimeZoneIDEnumeration)(
zone_type,
// Note that for the string pointer to remain valid, we must borrow the CString from
// asciiz_region, not move the CString out.
match &asciiz_region {
Some(asciiz_region) => asciiz_region.as_ptr(),
None => std::ptr::null(),
},
match raw_offset {
Some(_) => &mut repr_raw_offset,
None => std::ptr::null_mut(),
},
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(Enumeration {
_raw: None,
rep: raw_enum,
})
}
#[doc(hidden)]
/// Opens a list of available time zones.
///
/// Implements `ucal_openTimeZones`
// This should be in the `ucal` crate, but not possible because of the raw enum initialization.
// Tested in `ucal`.
pub fn open_time_zones() -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let raw_enum = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ucal_openTimeZones)(&mut status)
};
common::Error::ok_or_warning(status)?;
Ok(Enumeration {
_raw: None,
rep: raw_enum,
})
}
#[doc(hidden)]
// This has been moved to the `uloc` crate
#[deprecated(since="4.2.4", note="please use `ULoc::open_keywords` instead")]
pub fn uloc_open_keywords(locale: &str) -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz_locale = ffi::CString::new(locale)?;
let raw_enum = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(uloc_openKeywords)(asciiz_locale.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
// "No error but null" means that there are no keywords
if raw_enum.is_null() {
Ok(Enumeration::empty())
} else {
Ok(Enumeration {
_raw: None,
rep: raw_enum,
})
}
}
#[cfg(test)]
mod tests {
use {super::*, std::convert::TryFrom};
#[test]
fn iter() {
let e = Enumeration::try_from(&vec!["hello", "world", "💖"][..]).expect("enumeration?");
let mut count = 0;
let mut results = vec![];
for result in e {
let elem = result.expect("no error");
count += 1;
results.push(elem);
}
assert_eq!(count, 3, "results: {:?}", results);
assert_eq!(
results,
vec!["hello", "world", "💖"],
"results: {:?}",
results
);
}
#[test]
fn error() {
// A mutilated sparkle heart from https://doc.rust-lang.org/std/str/fn.from_utf8_unchecked.html
let destroyed_sparkle_heart = vec![0, 159, 164, 150];
let invalid_utf8 = unsafe { str::from_utf8_unchecked(&destroyed_sparkle_heart) };
let e = Enumeration::try_from(&vec!["hello", "world", "💖", invalid_utf8][..]);
assert!(e.is_err(), "was: {:?}", e);
}
#[test]
fn test_uloc_open_keywords() -> Result<(), common::Error> {
let loc = "az-Cyrl-AZ-u-ca-hebrew-fw-sunday-nu-deva-tz-usnyc";
#[allow(deprecated)]
let keywords: Vec<String> = uloc_open_keywords(loc).unwrap().map(|result| result.unwrap()).collect();
assert_eq!(
keywords,
vec![
"calendar".to_string(),
"fw".to_string(),
"numbers".to_string(),
"timezone".to_string()
]
);
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/lib.rs | ecma402_traits/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
/// This trait contains the common features of the Locale object that must be shared among
/// all the implementations. Every implementor of `listformat` should provide their
/// own version of [Locale], and should ensure that it implements [Locale]. as
/// specified here.
///
/// For the time being we agreed that a [Locale] *must* be convertible into its string
/// form, using `Display`.
pub trait Locale: fmt::Display {}
/// A Rust implementation of ECMA 402 ListFormat API.
///
/// The [listformat] mod contains all the needed implementation bits for `Intl.ListFormat`.
///
pub mod listformat;
/// A Rust implementation of ECMA 402 PluralRules API.
///
/// The [pluralrules] mod contains all the needed implementation bits for `Intl.PluralRules`.
pub mod pluralrules;
/// A Rust implementation of ECMA 402 NumberFormat API.
///
/// The [numberformat] mod contains all the needed implementation bits for `Intl.NumberFormat`.
pub mod numberformat;
/// A Rust implementation of the ECMA402 Collator API.
///
/// The [collator] mod contains all the needed implementation bits for `Intl.Collator`.
pub mod collator;
/// A Rust implementation of ECMA 402 DateTimeFormat API.
///
/// The [datetimeformat] mod contains all the needed implementation bits for `Intl.DateTimeFormat`.
pub mod datetimeformat;
/// A Rust implementation of ECMA 402 RelativeTimeFormat API.
///
/// The [relativetime] mod contains all the needed implementation bits for
/// `Intl.RelativeTimeFormat`.
pub mod relativetime;
/// A Rust implementation of ECMA 402 DisplayNames API.
///
/// The [displaynames] mod contains all the needed implementation bits for `Intl.DisplayNames`.
pub mod displaynames;
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/displaynames.rs | ecma402_traits/src/displaynames.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
/// Contains the API configuration as prescribed by [ECMA 402][ecma].
///
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [DisplayNames::try_new] for the use of
/// the options.
pub mod options {
/// The formatting style to use
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Style {
/// Example: "US".
Narrow,
/// Example: "USA".
Short,
/// Default. Example: "United States".
Long,
}
/// The type of the spellout. Spelled in the language of the
/// requested locale.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
/// The name of the language, e.g. "US English"
Language,
/// The name of the region, e.g. "United States".
Region,
/// The name of the script, e.g. "Latin",
Script,
/// The name of the currency, e.g. "US Dollar",
Currency,
}
/// The fallback to use.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Fallback {
/// Default: the fallback is the region code, e.g. "us"
Code,
/// No fallback.
None,
}
}
/// The options set by the user at construction time. Provides as a "bag of options" since we
/// don't expect any implementations to be attached to this struct.
///
/// The default values of all the options are prescribed by the TC39 report.
pub struct Options {
/// The formatting style to use.
pub style: options::Style,
/// The type of information to format.
pub in_type: options::Type,
/// Sets what to do if the information is not availabe.
pub fallback: options::Fallback,
}
impl Default for Options {
fn default() -> Options {
Options {
style: options::Style::Long,
in_type: options::Type::Region,
fallback: options::Fallback::Code,
}
}
}
/// Displays a region, language, script or currency using the language of
/// a specific locale.
pub trait DisplayNames {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [DisplayNames].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats the information about the given locale in the language used by
/// this [DisplayNames].
///
/// The function implements [`Intl.DisplayNames`][nfmt] from [ECMA 402][ecma].
///
/// [nfmt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn format<W, L>(&self, locale: L, writer: &mut W) -> fmt::Result
where
W: fmt::Write,
L: crate::Locale;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/relativetime.rs | ecma402_traits/src/relativetime.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
/// Contains the API configuration as prescribed by [ECMA 402][ecma].
///
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [RelativeTimeFormat::try_new]
/// for the use of the options.
pub mod options {
/// Whether to use numeric formatting in the display, like "1 day ago".
#[derive(Debug, Clone, PartialEq)]
pub enum Numeric {
/// Always use numeric formatting.
Always,
/// Allows not to use numeric formatting, and use "yesterday" instead of "1 day ago".
Auto,
}
/// The length of the internationalized message.
#[derive(Debug, Clone, PartialEq)]
pub enum Style {
/// Default, e.g. "in 1 month"
Long,
/// Short, e.g. "in 1 mo."
Short,
/// Short, e.g. "in 1 mo". The narrow style could be identical to [Style::Short] in some
/// locales.
Narrow,
}
}
/// The options set by the user at construction time.
///
/// Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
pub struct Options {
pub numeric: options::Numeric,
pub style: options::Style,
}
impl Default for Options {
fn default() -> Self {
Options {
numeric: options::Numeric::Auto,
style: options::Style::Long,
}
}
}
pub trait RelativeTimeFormat {
/// The type of the error reported, if any.
type Error: std::error::Error;
/// Creates a new [RelativeTimeFormat].
///
/// Creation may fail if the locale-specific data is not loaded, or if the supplied options are
/// inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats `days` into the supplied writer.
///
/// A positive value means days in the future. A negative value means days in the past.
///
/// The function implements [`Intl.RelativeDateFormat`][ref] from [ECMA 402][ecma].
///
/// [ref]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
///
fn format<W>(&self, days: i32, writer: &mut W) -> fmt::Result
where
W: fmt::Write;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/numberformat.rs | ecma402_traits/src/numberformat.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::fmt;
/// Contains the API configuration as prescribed by [ECMA 402][ecma].
///
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [NumberFormat::try_new]
/// for the use of the options.
pub mod options {
/// Controls whether short or long form display is used. Short is slightly
/// more economical with spacing. Only used when notation is Compact.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CompactDisplay {
/// Default.
Short,
/// Long display layout.
Long,
}
/// The ISO currency code for a currency, if the currency formatting is being used.
/// For example "EUR" or "USD".
///
/// The value entered as currency is not validated. This responsibility is
/// delegated to the implementor.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Currency(pub String);
impl From<&str> for Currency {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
/// Controls the display of currency information.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CurrencyDisplay {
/// Use a localized currency symbol such as €, this is the default value.
Symbol,
/// Narrow format symbol ("$100" rather than "US$100").
NarrowSymbol,
/// Use the ISO currency code.
Code,
/// Use a localized currency name, e.g. "dollar".
Name,
}
/// Controls the display of currency sign.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CurrencySign {
/// Uses accounting notation such as `($100)` to mean "minus one hundred dollars".
Accounting,
/// Uses standard notation such as `$-100`.
Standard,
}
/// Controls the number formatting.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Notation {
/// Example: 10,000.00. This is the default.
Standard,
/// Example: 1e+4
Scientific,
/// Example: 10k
Engineering,
/// Example: 10000
Compact,
}
/// Controls the number formatting.
///
/// Possible values include: "arab", "arabext", " bali", "beng", "deva", "fullwide", "gujr",
/// "guru", "hanidec", "khmr", " knda", "laoo", "latn", "limb", "mlym", " mong", "mymr",
/// "orya", "tamldec", " telu", "thai", "tibt".
///
/// The value entered as currency is not validated. This responsibility is
/// delegated to the implementor.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct NumberingSystem(pub String);
impl From<&str> for NumberingSystem {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
impl Default for NumberingSystem {
fn default() -> Self {
NumberingSystem("latn".to_string())
}
}
/// When to display the sign of the number.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum SignDisplay {
/// Display for negative numbers only.
Auto,
/// Never display the sign.
Never,
/// Always display the sign (even plus).
Always,
/// Display for positive and negative numbers, but not zero.
ExceptZero,
}
/// When to display the sign of the number.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Style {
/// For plain number formatting.
Decimal,
/// For currency formatting ("10 EUR")
Currency,
/// For percentage formatting ("10%")
Percent,
/// For unit formatting ("10 meters")
Unit,
}
/// The unit formatting style, when [Style::Unit] is used.
///
/// Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset
/// of units from the full list was selected for use in ECMAScript. Pairs of simple units can
/// be concatenated with "-per-" to make a compound unit. There is no default value; if the
/// style is "unit", the unit property must be provided.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum UnitDisplay {
/// "16 litres"
Long,
/// "16 l"
Short,
/// "16l"
Narrow,
}
/// The unit to use when [Style::Unit] is selected as [Style].
///
/// Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset
/// of units from the full list was selected for use in ECMAScript. Pairs of simple units can
/// be concatenated with "-per-" to make a compound unit. There is no default value; if the
/// style is "unit", the unit property must be provided.
#[derive(Debug, Clone)]
pub struct Unit(pub String);
}
/// The options set by the user at construction time. See discussion at the top level
/// about the name choice. Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
///
/// The default values of all the options are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-number-format/#sec-Intl.NumberFormat
#[derive(Debug, Clone)]
pub struct Options {
pub compact_display: Option<options::CompactDisplay>,
pub currency: Option<options::Currency>,
pub currency_display: options::CurrencyDisplay,
pub currency_sign: options::CurrencySign,
pub notation: options::Notation,
pub numbering_system: Option<options::NumberingSystem>,
pub sign_display: options::SignDisplay,
pub style: options::Style,
pub unit: Option<options::Unit>,
pub minimum_integer_digits: Option<u8>,
pub minimum_fraction_digits: Option<u8>,
pub maximum_fraction_digits: Option<u8>,
pub minimum_significant_digits: Option<u8>,
pub maximum_significant_digits: Option<u8>,
}
impl Default for Options {
/// Gets the default values of [Options] if omitted at setup. The
/// default values are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
fn default() -> Self {
Options {
compact_display: None,
currency: None,
currency_display: options::CurrencyDisplay::Symbol,
currency_sign: options::CurrencySign::Standard,
notation: options::Notation::Standard,
sign_display: options::SignDisplay::Auto,
style: options::Style::Decimal,
unit: None,
numbering_system: None,
minimum_integer_digits: None,
minimum_fraction_digits: None,
maximum_fraction_digits: None,
minimum_significant_digits: None,
maximum_significant_digits: None,
}
}
}
/// Formats number based on the rules configured on initialization.
pub trait NumberFormat {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [NumberFormat].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats `number` into the supplied `writer`.
///
/// The function implements [`Intl.NumberFormat`][nfmt] from [ECMA 402][ecma].
///
/// [nfmt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn format<W>(&self, number: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/listformat.rs | ecma402_traits/src/listformat.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Contains the API configuration as prescribed by ECMA 402.
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [Format::try_new]
/// for the use of the options.
pub mod options {
/// Chooses the list formatting approach.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Style {
Long,
Short,
Narrow,
}
/// Chooses between "this, that and other", and "this, that or other".
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
/// "This, that and other".
Conjunction,
/// "This, that or other".
Disjunction,
}
}
/// The options set by the user at construction time. See discussion at the top level
/// about the name choice. Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
///
/// The default values of all the options are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Options {
/// Selects a [options::Style] for the formatted list. If unset, defaults
/// to [options::Style::Long].
pub style: options::Style,
/// Selects a [options::Type] for the formatted list. If unset, defaults to
/// [options::Type::Conjunction].
pub in_type: options::Type,
}
/// Allows the use of `listformat::Format::try_new(..., Default::default())`.
impl Default for Options {
/// Gets the default values of [Options] if omitted at setup. The
/// default values are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
fn default() -> Self {
Options {
style: options::Style::Long,
in_type: options::Type::Conjunction,
}
}
}
use std::fmt;
/// The package workhorse: formats supplied pieces of text into an ergonomically formatted
/// list.
///
/// While ECMA 402 originally has functions under `Intl`, we probably want to
/// obtain a separate factory from each implementor.
///
/// Purposely omitted:
///
/// - `supported_locales_of`.
pub trait Format {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [Format].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats `list` into the supplied standard `writer` [fmt::Write].
///
/// The original [ECMA 402 function][ecma402fmt] returns a string. This is likely the only
/// reasonably generic option in JavaScript so it is adequate. In Rust, however, it is
/// possible to pass in a standard formatting strategy (through `writer`).
///
/// [ecma402fmt]:
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format
///
/// This makes it unnecessary for [Format] to implement its own, and can
/// completely avoid constructing any intermediary representation. This, in turn,
/// allows the user to provide a purpose built formatter, or a custom one if needed.
///
/// A purpose built formatter could be one that formats into a fixed-size buffer; or
/// another that knows how to format strings into a DOM. If ECMA 402 compatibility is
/// needed, the user can force formatting into a string by passing the appropriate
/// formatter.
///
/// > Note:
/// > - Should there be a convenience method that prints to string specifically?
/// > - Do we need `format_into_parts`?
fn format<I, L, W>(&self, list: L, writer: &mut W) -> fmt::Result
where
I: fmt::Display,
L: IntoIterator<Item = I>,
W: fmt::Write;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/collator.rs | ecma402_traits/src/collator.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Contains the API configuration as prescribed by ECMA 402.
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [Collator::try_new]
/// for the use of the options.
pub mod options {
/// Set the intended usage for this collation.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Usage {
/// Use collation for sorting. Default.
Sort,
/// Use collation for searching.
Search,
}
/// Set the sensitivity of the collation.
///
/// Which differences in the strings should lead to non-zero result values.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Sensitivity {
/// Only strings that differ in base letters compare as unequal.
/// Examples: a ≠ b, a = á, a = A.
Base,
/// Only strings that differ in base letters or accents and other diacritic marks compare
/// as unequal. Examples: a ≠ b, a ≠ á, a = A.
Accent,
/// Only strings that differ in base letters or case compare as unequal.
/// Examples: a ≠ b, a = á, a ≠ A.
Case,
/// Strings that differ in base letters, accents and other diacritic marks, or case compare
/// as unequal. Other differences may also be taken into consideration.
/// Examples: a ≠ b, a ≠ á, a ≠ A.
Variant,
}
/// Whether punctuation should be ignored.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Punctuation {
/// Ignore punctuation.
Ignore,
/// Honor punctuation.
Honor,
}
/// Whether numeric collation should be used, such that "1" < "2" < "10".
///
/// This option can be set through an options property or through a Unicode extension key; if
/// both are provided, the options property takes precedence. Implementations are not required
/// to support this property.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Numeric {
/// Use numeric comparison.
Use,
/// Do not use numeric comparision.
Ignore,
}
/// Whether upper case or lower case should sort first.
///
/// This option can be set through an options property or through a Unicode extension key; if
/// both are provided, the options property takes precedence. Implementations are not required
/// to support this property.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CaseFirst {
/// Sort upper case first.
Upper,
/// Sort lower case first.
Lower,
/// Use locale default for case sorting.
False,
}
}
/// The options set by the user at construction time. See discussion at the top level
/// about the name choice. Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
///
/// The default values of all the options are prescribed in by the [TC39 report][tc39].
///
/// [tc39]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Options {
pub usage: options::Usage,
pub sensitivity: options::Sensitivity,
pub punctuation: options::Punctuation,
pub numeric: options::Numeric,
pub case_first: options::CaseFirst,
}
impl Default for Options {
/// Gets the default values of [Options] if omitted at setup. The
/// default values are prescribed by the TC39. See [Collator][tc39c].
///
/// [tc39c]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator
fn default() -> Self {
Options {
usage: options::Usage::Sort,
sensitivity: options::Sensitivity::Variant,
punctuation: options::Punctuation::Honor,
numeric: options::Numeric::Ignore,
case_first: options::CaseFirst::False,
}
}
}
pub trait Collator {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [Collator].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Compares two strings according to the sort order of this [Collator].
///
/// Returns 0 if `first` and `second` are equal. Returns a negative value
/// if `first` is less, and a positive value of `second` is less.
fn compare<P, Q>(first: P, second: Q) -> i8
where
P: AsRef<str>,
Q: AsRef<str>;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/pluralrules.rs | ecma402_traits/src/pluralrules.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Contains the API configuration as prescribed by [ECMA 402][ecma].
///
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [Options] for the contents of the options. See the [PluralRules::try_new]
/// for the use of the options.
pub mod options {
/// The type of plural rules with respect to cardinality and ordinality.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
/// As in "one, two, three, ..."
Cardinal,
/// As in: "first, second, third, ..."
Ordinal,
}
}
/// The options set by the user at construction time. See discussion at the top level
/// about the name choice. Provides as a "bag of options" since we don't expect any
/// implementations to be attached to this struct.
///
/// The default values of all the options are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Options {
/// Selects a [options::Type] for the formatted list. If unset, defaults to
/// [options::Type::Cardinal].
pub in_type: options::Type,
pub minimum_integer_digits: u8,
pub minimum_fraction_digits: u8,
pub maximum_fraction_digits: u8,
pub minimum_significant_digits: u8,
pub maximum_significant_digits: u8,
}
/// Allows the use of `pluralrules::Rules::try_new(..., Default::default())`.
impl Default for Options {
/// Gets the default values of [Options] if omitted at setup. The
/// default values are prescribed in by the [TC39 report][tc39lf].
///
/// [tc39lf]: https://tc39.es/proposal-intl-list-format/#sec-Intl.ListFormat
fn default() -> Self {
Options {
in_type: options::Type::Cardinal,
minimum_integer_digits: 1,
minimum_fraction_digits: 0,
maximum_fraction_digits: 3,
minimum_significant_digits: 1,
maximum_significant_digits: 21,
}
}
}
use std::fmt;
/// Returns the plural class of each of the supplied number.
pub trait PluralRules {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [PluralRules].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: Options) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats the plural class of `number` into the supplied `writer`.
///
/// The function implements [`Intl.PluralRules`][plr] from [ECMA 402][ecma].
///
/// [plr]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules
/// [ecma]: https://www.ecma-international.org/publications/standards/Ecma-402.htm
fn select<W>(&self, number: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/ecma402_traits/src/datetimeformat.rs | ecma402_traits/src/datetimeformat.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::num;
/// Contains the API configuration as prescribed by ECMA 402.
///
/// The meaning of the options is the same as in the similarly named
/// options in the JS version.
///
/// See [DateTimeFormatOptions] for the contents of the options. See the [DateTimeFormat::try_new]
/// for the use of the options.
pub mod options {
use std::fmt;
/// The date and time formatting options.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Style {
/// Full length format style.
///
/// * Date: "Wednesday, December 19, 2012"
/// * Time: "7:00:00 PM Pacific Standard Time"
Full,
/// Long length format style.
///
/// * Date: "December 19, 2012"
/// * Time: "7:00:00 PM PST"
Long,
/// Medium length format style.
///
/// * Date: "Dec 19, 2012"
/// * Time: "7:00:00 PM"
Medium,
/// Short length format style.
///
/// * Date: "12/29/12"
/// * "7:00 PM"
Short,
}
/// Controls the calendar to use.
///
/// Possible values include: "buddhist", "chinese", " coptic", "ethiopia", "ethiopic",
/// "gregory", " hebrew", "indian", "islamic", "iso8601", " japanese", "persian", "roc".
///
/// The value entered as currency is not validated. This responsibility is
/// delegated to the implementor.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Calendar(pub String);
impl Default for Calendar {
fn default() -> Self {
Self("gregory".into())
}
}
impl From<&str> for Calendar {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
/// The way day periods (morning, afternoon) should be expressed.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum DayPeriod {
/// "AM", "PM"
Narrow,
/// "A.M.", "P.M".
Short,
/// "Morning", "Afternoon".
Long,
}
/// Controls the number formatting.
///
/// Possible values include: "arab", "arabext", " bali", "beng", "deva", "fullwide", "gujr",
/// "guru", "hanidec", "khmr", " knda", "laoo", "latn", "limb", "mlym", " mong", "mymr",
/// "orya", "tamldec", " telu", "thai", "tibt".
///
/// The value entered is not validated. This responsibility is delegated to the implementor.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct NumberingSystem(pub String);
impl From<&str> for NumberingSystem {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
impl Default for NumberingSystem {
fn default() -> Self {
Self("latn".to_string())
}
}
/// Controls the time zone formatting.
///
/// The value entered is not validated. This responsibility is delegated to the implementor.
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct TimeZone(pub String);
impl From<&str> for TimeZone {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
impl Default for TimeZone {
fn default() -> Self {
Self("UTC".to_string())
}
}
/// The hour cycle to use
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum HourCycle {
/// 12 hour cycle, 0..11.
H11,
/// 12 hour cycle, 1..12.
H12,
/// 4 hour cycle, 0..23.
H23,
/// 4 hour cycle, 1..24.
H24,
}
impl fmt::Display for HourCycle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HourCycle::H11 => write!(f, "h11"),
HourCycle::H12 => write!(f, "h12"),
HourCycle::H23 => write!(f, "h23"),
HourCycle::H24 => write!(f, "h24"),
}
}
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Weekday {
/// "Thursday"
Long,
/// "Thu",
Short,
/// "T",
Narrow,
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Era {
/// "Anno Domini"
Long,
/// "AD",
Short,
/// "A",
Narrow,
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum DisplaySize {
/// "2012"
Numeric,
/// "12"
TwoDigit,
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Month {
/// "3"
Numeric,
/// "03",
TwoDigit,
/// "March",
Long,
/// "Mar"
Short,
/// "M"
Narrow,
}
/// The time zone name styling to use.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum TimeZoneStyle {
/// "British Summer Time"
Long,
/// "GMT+1"
Short,
}
}
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct DateTimeFormatOptions {
/// The formatting style to use for formatting the date part.
/// If `date_style` or `time_style` are set, none of the other options
/// are acceptable.
pub date_style: Option<options::Style>,
/// The formatting style to use for formatting the time part.
/// If `date_style` or `time_style` are set, none of the other options
/// are acceptable.
pub time_style: Option<options::Style>,
/// The number of fractional seconds to apply when calling `format`.
/// Valid values are 1 to 3.
pub fractional_second_digits: Option<num::NonZeroU8>,
/// If left unspecified, the locale default is used.
pub calendar: Option<options::Calendar>,
/// If left unspecified, the locale default is used.
pub day_period: Option<options::DayPeriod>,
/// If left unspecified, the locale default is used.
pub numbering_system: Option<options::NumberingSystem>,
/// If left unspecified, the locale default is used.
pub time_zone: Option<options::TimeZone>,
/// If left unspecified, the locale default is used.
pub hour_cycle: Option<options::HourCycle>,
/// If left unspecified, the locale default is used.
pub weekday: Option<options::Weekday>,
/// If left unspecified, the locale default is used.
pub era: Option<options::Era>,
/// If left unspecified, the locale default is used.
pub year: Option<options::DisplaySize>,
/// If left unspecified, the locale default is used.
pub month: Option<options::Month>,
/// If left unspecified, the locale default is used.
pub day: Option<options::DisplaySize>,
/// If left unspecified, the locale default is used.
pub hour: Option<options::DisplaySize>,
/// If left unspecified, the locale default is used.
pub minute: Option<options::DisplaySize>,
/// If left unspecified, the locale default is used.
pub second: Option<options::DisplaySize>,
/// If left unspecified, the locale default is used.
pub time_zone_style: Option<options::TimeZoneStyle>,
}
impl Default for DateTimeFormatOptions {
fn default() -> Self {
Self {
date_style: None,
time_style: None,
fractional_second_digits: None,
day_period: None,
numbering_system: None,
calendar: None,
time_zone: None,
hour_cycle: None,
weekday: None,
era: None,
year: None,
month: None,
day: None,
hour: None,
minute: None,
second: None,
time_zone_style: None,
}
}
}
use std::fmt;
pub trait DateTimeFormat {
/// The type of error reported, if any.
type Error: std::error::Error;
/// Creates a new [DateTimeFormat].
///
/// Creation may fail, for example, if the locale-specific data is not loaded, or if
/// the supplied options are inconsistent.
fn try_new<L>(l: L, opts: DateTimeFormatOptions) -> Result<Self, Self::Error>
where
L: crate::Locale,
Self: Sized;
/// Formats `date` into the supplied standard `writer` [fmt::Write].
///
/// The original [ECMA 402 function][ecma402fmt] returns a string. This is likely the only
/// reasonably generic option in JavaScript so it is adequate. In Rust, however, it is
/// possible to pass in a standard formatting strategy (through `writer`).
///
/// [ecma402fmt]:
/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format
///
/// The `date` holds the number of seconds (with fractional part) since the beginning of the
/// Unix epoch. The date is a very generic type because there is no official date-time type
/// in Rust.
fn format<W>(&self, date: f64, writer: &mut W) -> fmt::Result
where
W: fmt::Write;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_unumberformatter/src/lib.rs | rust_icu_unumberformatter/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU number formatting support for rust (modern)
//!
//! Since 0.3.1
use {
rust_icu_common as common,
rust_icu_common::simple_drop_impl,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_uloc as uloc, rust_icu_unum as unum, rust_icu_ustring as ustring,
rust_icu_ustring::buffered_uchar_method_with_retry,
std::{convert::TryFrom, convert::TryInto, ptr},
};
macro_rules! format_type {
($method_name:ident, $impl_function_name:ident, $value_type:ty) => {
#[doc = concat!("Implements `", stringify!($impl_function_name), "`. Since 0.3.1.")]
pub fn $method_name(&self, value: $value_type) -> Result<UFormattedNumber, common::Error> {
let mut result = UFormattedNumber::try_new()?;
let mut status = sys::UErrorCode::U_ZERO_ERROR;
unsafe {
versioned_function!($impl_function_name)(
self.rep.as_ptr(),
value,
result.as_c_mut_ptr(),
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(result)
}
};
}
/// The struct for modern number formatting (akin to ECMA402).
///
/// Use [UNumberFormatter::try_new] to create a new instance of this type.
#[derive(Debug)]
pub struct UNumberFormatter {
rep: ptr::NonNull<sys::UNumberFormatter>,
}
simple_drop_impl!(UNumberFormatter, unumf_close);
impl UNumberFormatter {
/// Makes a new [UNumberFormatter], using ICU types.
///
/// To make a new formatter if you have Rust types only, see [UNumberFormatter::try_new]. See
/// that function also for the description of skeleton syntax.
///
/// Returns the error description if an error is found.
///
/// Implements `unumf_openForSkeletonAndLocaleWithError`. Since 0.3.1.
/// Implements `unumf_openForSkeletonAndLocale`. Since 0.3.1.
pub fn try_new_ustring(
skeleton: &ustring::UChar,
locale: &uloc::ULoc,
) -> Result<UNumberFormatter, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
// Uses the "with error" flavor of the constructor for ICU versions upwards of
// 64. This allows more elaborate error messages in case of an issue.
#[cfg(feature = "icu_version_64_plus")]
{
let mut parse_status = common::NO_PARSE_ERROR.clone();
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unumf_openForSkeletonAndLocaleWithError)(
skeleton.as_c_ptr(),
skeleton.len() as i32,
locale.label().as_ptr() as *const std::os::raw::c_char,
&mut parse_status,
&mut status,
)
};
assert_ne!(rep, 0 as *mut sys::UNumberFormatter);
common::parse_ok(parse_status)?;
common::Error::ok_or_warning(status)?;
let result = UNumberFormatter {
rep: std::ptr::NonNull::new(rep).unwrap(),
};
return Ok(result);
}
#[cfg(not(feature = "icu_version_64_plus"))]
{
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unumf_openForSkeletonAndLocale)(
skeleton.as_c_ptr(),
skeleton.len() as i32,
locale.label().as_ptr() as *const std::os::raw::c_char,
&mut status,
)
};
assert_ne!(rep, 0 as *mut sys::UNumberFormatter);
common::Error::ok_or_warning(status)?;
let result = UNumberFormatter {
rep: std::ptr::NonNull::new(rep).unwrap(),
};
return Ok(result);
}
}
/// Similar to [UNumberFormatter::try_new_ustring] but uses Rust types.
///
/// The `skeleton` is a string that describes the formatting options.
/// See [skeleton syntax][skel] for detailed documentation.
///
/// Implements `unumf_openForSkeletonAndLocaleWithError`. Since 0.3.1.
/// Implements `unumf_openForSkeletonAndLocale`. Since 0.3.1.
///
/// [skel]: https://github.com/unicode-org/icu/blob/%6d%61%73%74%65%72/docs/userguide/format_parse/numbers/skeletons.md
pub fn try_new(skeleton: &str, locale: &str) -> Result<UNumberFormatter, common::Error> {
let locale = uloc::ULoc::try_from(locale)?;
let skeleton = ustring::UChar::try_from(skeleton)?;
UNumberFormatter::try_new_ustring(&skeleton, &locale)
}
// Implements `unumf_formatInt`. Since 0.3.1.
format_type!(format_int, unumf_formatInt, i64);
// Implements `unumf_formatDouble`. Since 0.3.1.
format_type!(format_double, unumf_formatDouble, f64);
/// Implements `unumf_formatDecimal`. Since 0.3.1.
pub fn format_decimal(&self, value: &str) -> Result<UFormattedNumber, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let mut result = UFormattedNumber::try_new()?;
unsafe {
versioned_function!(unumf_formatDecimal)(
self.rep.as_ptr(),
value.as_ptr() as *const std::os::raw::c_char,
value.len() as i32,
result.as_c_mut_ptr(),
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(result)
}
}
/// Stores a formatted number result.
///
/// These objects are produced [UNumberFormatter::format_int], [UNumberFormatter::format_double],
/// [UNumberFormatter::format_decimal].
///
#[derive(Debug)]
pub struct UFormattedNumber {
rep: std::ptr::NonNull<sys::UFormattedNumber>,
}
impl UFormattedNumber {
/// Implements `unumf_openResult`. Since 0.3.1.
fn try_new() -> Result<Self, common::Error> {
let mut status = sys::UErrorCode::U_ZERO_ERROR;
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(unumf_openResult)(&mut status)
};
common::Error::ok_or_warning(status)?;
assert_ne!(rep, 0 as *mut sys::UFormattedNumber);
let result = std::ptr::NonNull::new(rep).unwrap();
Ok(UFormattedNumber { rep: result })
}
/// Reveals the underlying C representation.
fn as_c_mut_ptr(&mut self) -> *mut sys::UFormattedNumber {
self.rep.as_ptr()
}
/// Reveals the underlying C representation.
fn as_c_ptr(&self) -> *const sys::UFormattedNumber {
self.rep.as_ptr()
}
/// Obtains the field iterator for the formatted result.
///
/// Implements `unumf_resultGetAllFieldPositions`. Since 0.3.1.
///
/// Implements `unumf_resultNextFieldPosition`. Since 0.3.1. All access is
/// via iterators.
pub fn try_field_iter<'a>(
&'a self,
) -> Result<unum::UFieldPositionIterator<'a, Self>, common::Error> {
let mut result = unum::UFieldPositionIterator::try_new_owned(self)?;
let mut status = sys::UErrorCode::U_ZERO_ERROR;
unsafe {
versioned_function!(unumf_resultGetAllFieldPositions)(
self.as_c_ptr(),
result.as_mut_ptr(),
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(result)
}
}
simple_drop_impl!(UFormattedNumber, unumf_closeResult);
impl TryInto<ustring::UChar> for UFormattedNumber {
type Error = common::Error;
/// Converts this formatted number into a Unicode string.
///
/// You want to use this method instead of `TryInto<String>` when you need
/// to do additional processing on the result, such as extracting fields
/// based on their indexes.
///
/// Implements `unumf_resultToString`. Since 0.3.1.
fn try_into(self) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
tryinto_impl,
CAPACITY,
[rep: *const sys::UFormattedNumber,],
[]
);
tryinto_impl(versioned_function!(unumf_resultToString), self.rep.as_ptr())
}
}
impl TryInto<String> for UFormattedNumber {
type Error = common::Error;
/// Converts this formatted number into a Rust string.
///
/// If you intend to use field position iterators on the result, you have to use
/// `TryInto<ustring::UChar>` instead, because field position iterators use the fixed encoding
/// of [ustring::UChar] for positioning.
///
/// Implements `unumf_resultToString`. Since 0.3.1.
fn try_into(self) -> Result<String, common::Error> {
let result: ustring::UChar = self.try_into()?;
String::try_from(&result)
}
}
#[cfg(test)]
mod testing {
use std::convert::TryInto;
#[test]
fn basic() {
let fmt = super::UNumberFormatter::try_new(
"measure-unit/length-meter compact-long sign-always",
"sr-RS",
)
.unwrap();
let result = fmt.format_double(123456.7890).unwrap();
let result_str: String = result.try_into().unwrap();
assert_eq!("+123 хиљаде m", result_str);
// Quickly check that the value is as expected.
let result = fmt.format_double(123456.7890).unwrap();
let num_fields = result.try_field_iter().unwrap().count();
assert!(num_fields > 0);
}
#[test]
fn thorough() {
#[derive(Debug, Clone)]
struct TestCase {
locale: &'static str,
number: f64,
skeleton: &'static str,
expected: &'static str,
}
let tests = vec![
TestCase {
locale: "sr-RS",
number: 123456.7890,
skeleton: "measure-unit/length-meter compact-long sign-always",
expected: "+123 хиљаде m",
},
TestCase {
locale: "sr-RS-u-nu-deva",
number: 123456.7890,
skeleton: "measure-unit/length-meter compact-long sign-always",
expected: "+१२३ хиљаде m",
},
TestCase {
locale: "sr-RS",
number: 123456.7890,
skeleton: "numbering-system/deva",
expected: "१२३.४५६,७८९",
},
TestCase {
locale: "en-IN",
number: 123456.7890,
skeleton: "@@@",
expected: "1,23,000",
},
];
for test in tests {
let fmt = super::UNumberFormatter::try_new(&test.skeleton, &test.locale)
.expect(&format!("for test {:?}", &test));
let result = fmt.format_double(test.number).unwrap();
let result_str: String = result.try_into().unwrap();
assert_eq!(test.expected, result_str, "for test {:?}", &test);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_uformattable/src/lib.rs | rust_icu_uformattable/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU number formatting support for rust
use {
rust_icu_common as common, rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_ustring as ustring,
std::{convert::TryFrom, ffi, os::raw, ptr},
};
// Implements the ICU type [`UFormattable`][ufmt].
//
// [UFormattable] is a thin wrapper for primitive types used for number formatting.
//
// Note from the ICU4C API:
//
// > Underlying is a C interface to the class `icu::Formatable`. Static functions
// on this class convert to and from this interface (via `reinterpret_cast`). Many
// operations are not thread safe, and should not be shared between threads.
//
// [ufmt]: https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/uformattable_8h.html
#[derive(Debug)]
pub struct UFormattable<'a> {
// The underlying representation.
rep: ptr::NonNull<sys::UFormattable>,
owner: Option<&'a Self>,
}
impl<'a> Drop for crate::UFormattable<'a> {
/// Implements `ufmt_close`.
fn drop(&mut self) {
if let None = self.owner {
unsafe { versioned_function!(ufmt_close)(self.rep.as_ptr()) };
}
}
}
/// Generates a simple getter, which just shunts into an appropriately
/// named getter function of the sys crate and returns the appropriate type.
///
/// Example:
///
/// ```ignore
/// simple_getter!(get_array_length, ufmt_getArrayLength, i32);
/// ```
///
/// * `$method_name` is an identifier
macro_rules! simple_getter {
($method_name:ident, $impl_function_name:ident, $return_type:ty) => {
#[doc = concat!("Implements `", stringify!($impl_function_name), "`.")]
///
/// Use [UFormattable::get_type] to verify that the type matches.
pub fn $method_name(&self) -> Result<$return_type, common::Error> {
let mut status = common::Error::OK_CODE;
let ret = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!($impl_function_name)(self.rep.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(ret)
}
};
}
impl<'a> crate::UFormattable<'a> {
/// Initialize a [crate::UFormattable] to type `UNUM_LONG`, value 0 may
/// return error.
///
/// Implements `ufmt_open`.
pub fn try_new<'b>() -> Result<crate::UFormattable<'b>, common::Error> {
let mut status = common::Error::OK_CODE;
// We verify that status is OK on entry and on exit, and that the
// returned representation is not null.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ufmt_open)(&mut status)
};
common::Error::ok_or_warning(status)?;
Ok(UFormattable {
rep: ptr::NonNull::new(rep).unwrap(),
owner: None,
})
}
/// Reveals the underlying representation as a mutable pointer.
///
/// **DO NOT USE UNLESS YOU HAVE NO OTHER CHOICE**
///
/// The intended use of this method is for other crates that need to obtain
/// low-level representations of this type.
#[doc(hidden)]
pub fn as_mut_ptr(&mut self) -> *mut sys::UFormattable {
self.rep.as_ptr()
}
pub fn as_ptr(&self) -> *const sys::UFormattable {
self.rep.as_ptr()
}
/// Returns `true` if this formattable is numeric.
///
/// Implements `ufmt_isNumeric`
pub fn is_numeric(&self) -> bool {
let ubool = unsafe { versioned_function!(ufmt_isNumeric)(self.rep.as_ptr()) };
match ubool {
0i8 => false,
_ => true,
}
}
// Returns the type of this formattable. The comment here and below is
// used in coverage analysis; the macro `simple_getter!` generates
// user-visible documentation.
//
// Implements `ufmt_getType`
simple_getter!(get_type, ufmt_getType, sys::UFormattableType);
// Implements `ufmt_getDate`
simple_getter!(get_date, ufmt_getDate, sys::UDate);
// Implements `ufmt_getDouble`
simple_getter!(get_double, ufmt_getDouble, f64);
// Implements `ufmt_getLong`
simple_getter!(get_i32, ufmt_getLong, i32);
// Implements `ufmt_getInt64`
simple_getter!(get_i64, ufmt_getInt64, i64);
// Implements `ufmt_getArrayLength`
simple_getter!(get_array_length, ufmt_getArrayLength, i32);
// Implements `ufmt_getUChars`
pub fn get_ustring(&self) -> Result<ustring::UChar, common::Error> {
let mut status = common::Error::OK_CODE;
let mut ustrlen = 0i32;
let raw = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ufmt_getUChars)(self.rep.as_ptr(), &mut ustrlen, &mut status)
} as *mut sys::UChar;
common::Error::ok_or_warning(status)?;
let ret = unsafe {
assert_ne!(raw, 0 as *mut sys::UChar);
assert!(ustrlen >= 0);
ustring::UChar::clone_from_raw_parts(raw, ustrlen)
};
Ok(ret)
}
/// Implements `ufmt_getUChars`
pub fn get_str(&self) -> Result<String, common::Error> {
let ustr = self.get_ustring()?;
String::try_from(&ustr)
}
/// Use [UFormattable::get_type] to ensure that this formattable is an array before using this
/// method. Otherwise you will get an error. The lifetime of the resulting formattable is tied
/// to this one.
///
/// Implements `ufmt_getArrayItemByIndex`
pub fn get_array_item_by_index(
&'a self,
index: i32,
) -> Result<crate::UFormattable<'a>, common::Error> {
let mut status = common::Error::OK_CODE;
let raw: *mut sys::UFormattable = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ufmt_getArrayItemByIndex)(self.rep.as_ptr(), index, &mut status)
};
common::Error::ok_or_warning(status)?;
assert_ne!(raw, 0 as *mut sys::UFormattable);
Ok(UFormattable {
rep: ptr::NonNull::new(raw).unwrap(),
owner: Some(&self),
})
}
/// Implements `ufmt_getDecNumChars`
pub fn get_dec_num_chars(&self) -> Result<String, common::Error> {
let mut status = common::Error::OK_CODE;
let mut cstrlen = 0i32;
let raw: *const raw::c_char = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ufmt_getDecNumChars)(self.rep.as_ptr(), &mut cstrlen, &mut status)
};
common::Error::ok_or_warning(status)?;
let ret = unsafe {
assert_ne!(raw, 0 as *const raw::c_char);
assert!(cstrlen >= 0);
ffi::CStr::from_ptr(raw)
};
Ok(ret
.to_str()
.map_err(|e: std::str::Utf8Error| common::Error::from(e))?
.to_string())
}
}
#[cfg(test)]
mod tests {
use crate::*;
// There doesn't seem to be a way to initialize a nonzero Numeric for testing all of this code.
// So it seems it would have to remain uncovered with tests, until some other code gets to
// use it.
#[test]
fn basic() {
let n = crate::UFormattable::try_new().expect("try_new");
assert_eq!(
sys::UFormattableType::UFMT_LONG,
n.get_type().expect("get_type")
);
assert_eq!(0, n.get_i32().expect("get_i32"));
assert_eq!("0", n.get_dec_num_chars().expect("get_dec_num_chars"));
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_utext/src/lib.rs | rust_icu_utext/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function,
rust_icu_sys::*, std::cmp::Eq, std::convert::TryFrom, std::os::raw,
};
#[derive(Debug)]
pub struct Text {
// rep is allocated by the underlying library and has to be dropped using `utext_close`.
rep: *mut UText,
}
impl PartialEq for Text {
fn eq(&self, other: &Self) -> bool {
let ret = unsafe { versioned_function!(utext_equals)(self.rep, other.rep) };
match ret {
0 => false,
1 => true,
// Could be a bug in the underlying library.
_ => panic!("value is not convertible to bool in Text::eq: {}", ret),
}
}
}
impl Eq for Text {}
impl TryFrom<String> for Text {
type Error = common::Error;
/// Produces a unicode Text from a rust String.
///
/// The conversion may fail if the string is not well formed, and may result in an error.
///
/// Implements `utext_open` from ICU4C.
fn try_from(s: String) -> Result<Self, Self::Error> {
let len: i64 = s.len() as i64;
let bytes = s.as_ptr() as *const raw::c_char;
// bytes and len must be compatible. Ensured by the two lines just above.
unsafe { Self::from_raw_bytes(bytes, len) }
}
}
impl TryFrom<&str> for Text {
type Error = common::Error;
/// Implements `utext_open`
fn try_from(s: &str) -> Result<Self, Self::Error> {
let len = s.len() as i64;
let bytes = s.as_ptr() as *const raw::c_char;
// bytes and len must be compatible. Ensured by the two lines just above.
unsafe { Self::from_raw_bytes(bytes, len) }
}
}
impl Text {
/// Constructs the Text from raw byte contents.
///
/// The expectation is that the buffer and length are valid and compatible. That is,
/// that buffer is a valid pointer, that it points to an allocated buffer and that the length
/// of the allocated buffer is exactly `len`.
unsafe fn from_raw_bytes(buffer: *const raw::c_char, len: i64) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
// Requires that 'bytes' is a valid pointer and len is the correct length of 'bytes'.
let rep = versioned_function!(utext_openUTF8)(0 as *mut UText, buffer, len, &mut status);
common::Error::ok_or_warning(status)?;
Ok(Text { rep })
}
/// Tries to produce a clone of this Text.
///
/// If `deep` is set, a deep clone is made. This is not a Clone trait since
/// this clone is parameterized, and may fail.
///
/// Implements `utext_clone` from ICU4C.
pub fn try_clone(&self, deep: bool, readonly: bool) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
// Requires that 'src' be a valid pointer.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(utext_clone)(
0 as *mut UText,
self.rep,
deep as sys::UBool,
readonly as sys::UBool,
&mut status,
)
};
common::Error::ok_or_warning(status)?;
Ok(Text { rep })
}
}
impl Drop for Text {
/// Implements `utext_close` from ICU4C.
fn drop(&mut self) {
// Requires that self.rep is a valid pointer.
unsafe {
versioned_function!(utext_close)(self.rep);
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn partial_eq() {
let foo = Text::try_from("foo".to_string()).expect("conversion from string succeeds.");
let bar = Text::try_from("foo").expect("conversion from literal succeeds");
let baz = Text::try_from("baz").expect("conversion from literal succeeds");
// Should all be equal to themselves.
assert_eq!(1i8, unsafe {
versioned_function!(utext_equals)(foo.rep, foo.rep)
});
assert_eq!(1i8, unsafe {
versioned_function!(utext_equals)(bar.rep, bar.rep)
});
// Should not be equal since not the same text and position.
assert_ne!(1i8, unsafe {
versioned_function!(utext_equals)(foo.rep, bar.rep)
});
assert_ne!(foo, bar);
assert_ne!(foo, baz);
assert_ne!(bar, baz);
assert_eq!(
foo,
foo.try_clone(true, true).expect("clone is a success"),
"a clone should be the same as its source"
);
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_ulistformatter/src/lib.rs | rust_icu_ulistformatter/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU list formatting support for rust
//!
//! This crate provides locale-sensitive list formatting, based on the list
//! formatting as implemente by the ICU library. Specifically, the functionality
//! exposed through its C API, as available in the [header `ulisetformatter.h`][header].
//!
//! [header]: https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ulistformatter_8h.html
//!
//! > Are you missing some features from this crate? Consider [reporting an
//! issue](https://github.com/google/rust_icu/issues) or even [contributing the
//! functionality](https://github.com/google/rust_icu/pulls).
//!
//! ## Examples
//!
//! > TBD
use {
rust_icu_common as common, rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_ustring as ustring,
std::{convert::TryFrom, convert::TryInto, ffi, ptr},
};
#[derive(Debug)]
pub struct UListFormatter {
rep: ptr::NonNull<sys::UListFormatter>,
}
impl Drop for UListFormatter {
/// Implements ulistfmt_close`.
fn drop(&mut self) {
unsafe { versioned_function!(ulistfmt_close)(self.rep.as_ptr()) };
}
}
impl UListFormatter {
/// Implements ulistfmt_open`.
pub fn try_new(locale: &str) -> Result<UListFormatter, common::Error> {
let locale_cstr = ffi::CString::new(locale)?;
let mut status = common::Error::OK_CODE;
// Unsafety note: this is the way to create the formatter. We expect all
// the passed-in values to be well-formed.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ulistfmt_open)(locale_cstr.as_ptr(), &mut status)
as *mut sys::UListFormatter
};
common::Error::ok_or_warning(status)?;
Ok(UListFormatter {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Implements `ulistfmt_openForType`. Since ICU 67.
#[cfg(feature = "icu_version_67_plus")]
pub fn try_new_styled(
locale: &str,
format_type: sys::UListFormatterType,
format_width: sys::UListFormatterWidth,
) -> Result<UListFormatter, common::Error> {
let locale_cstr = ffi::CString::new(locale)?;
let mut status = common::Error::OK_CODE;
// Unsafety note: this is the way to create the formatter. We expect all
// the passed-in values to be well-formed.
let rep = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ulistfmt_openForType)(
locale_cstr.as_ptr(),
format_type,
format_width,
&mut status,
) as *mut sys::UListFormatter
};
common::Error::ok_or_warning(status)?;
Ok(UListFormatter {
rep: ptr::NonNull::new(rep).unwrap(),
})
}
/// Implements `ulistfmt_format`.
pub fn format(&self, list: &[&str]) -> Result<String, common::Error> {
let result = self.format_uchar(list)?;
String::try_from(&result)
}
/// Implements `ulistfmt_format`.
// TODO: this method call is repetitive, and should probably be pulled out into a macro.
// TODO: rename this function into format_uchar.
pub fn format_uchar(&self, list: &[&str]) -> Result<ustring::UChar, common::Error> {
let list_ustr = UCharArray::try_from(list)?;
const CAPACITY: usize = 200;
let (pointers, strlens, len) = unsafe { list_ustr.as_pascal_strings() };
// This is similar to buffered_string_method_with_retry, except the buffer
// consists of [sys::UChar]s.
let mut status = common::Error::OK_CODE;
let mut buf: Vec<sys::UChar> = vec![0; CAPACITY];
let full_len: i32 = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(ulistfmt_format)(
self.rep.as_ptr(),
pointers as *const *const sys::UChar,
strlens as *const i32,
len as i32,
buf.as_mut_ptr(),
CAPACITY as i32,
&mut status,
)
};
if status == sys::UErrorCode::U_BUFFER_OVERFLOW_ERROR
|| (common::Error::is_ok(status)
&& full_len > CAPACITY.try_into().map_err(|e| common::Error::wrapper(e))?)
{
status = common::Error::OK_CODE;
assert!(full_len > 0);
let full_len: usize = full_len.try_into().map_err(|e| common::Error::wrapper(e))?;
buf.resize(full_len, 0);
unsafe {
assert!(common::Error::is_ok(status), "status: {:?}", status);
versioned_function!(ulistfmt_format)(
self.rep.as_ptr(),
pointers as *const *const sys::UChar,
strlens as *const i32,
len as i32,
buf.as_mut_ptr(),
buf.len() as i32,
&mut status,
)
};
}
common::Error::ok_or_warning(status)?;
if full_len >= 0 {
let full_len: usize = full_len.try_into().map_err(|e| common::Error::wrapper(e))?;
buf.resize(full_len, 0);
}
Ok(ustring::UChar::from(buf))
}
}
/// A helper array that deconstructs [ustring::UChar] into constituent raw parts
/// that can be passed into formatting functions that use array APIs for parameter-passing.
///
/// Create with [UCharArray::try_from], and then use [UCharArray::as_pascal_strings] to get
/// the respective sizes.
#[derive(Debug)]
struct UCharArray {
// The elements of the array.
elements: Vec<ustring::UChar>,
// Pointers to the respective elements.
pointers: Vec<*const sys::UChar>,
// The string lengths (in ustring::UChar units) of respective elements.
// These strlens are what `listfmt_format` expects, so can't be `usize` but
// *must* be `i32`.
strlens: Vec<i32>,
}
impl<T> TryFrom<&[T]> for UCharArray
where
T: AsRef<str>,
{
type Error = common::Error;
/// Creates a new [UCharArray] from an array of string-like types.
fn try_from(list: &[T]) -> Result<Self, Self::Error> {
let mut elements: Vec<ustring::UChar> = Vec::with_capacity(list.len());
for element in list {
let uchar = ustring::UChar::try_from(element.as_ref())?;
elements.push(uchar);
}
let pointers = elements.iter().map(|e| e.as_c_ptr()).collect();
let strlens = elements.iter().map(|e| e.len() as i32).collect();
Ok(UCharArray {
elements,
pointers,
strlens,
})
}
}
impl AsRef<Vec<ustring::UChar>> for UCharArray {
fn as_ref(&self) -> &Vec<ustring::UChar> {
&self.elements
}
}
impl UCharArray {
/// Returns the elements of the array decomposed as "pascal strings", i.e.
/// separating out the pointers, the sizes of each individual string included,
/// and the total size of the array.
pub unsafe fn as_pascal_strings(self) -> (*mut *mut sys::UChar, *mut *mut i32, usize) {
let pointers = self.pointers.as_ptr() as *mut *mut sys::UChar;
let strlens = self.strlens.as_ptr() as *mut *mut i32;
let len = self.elements.len();
// Since 'self' was not moved anywhere in this method, we need to forget it before we
// return pointers to its content, else all the pointers will be invalidated.
std::mem::forget(self);
(pointers, strlens, len)
}
/// Returns the number of elements in the array.
#[allow(dead_code)] // Not used in production code yet.
pub fn len(&self) -> usize {
self.elements.len()
}
/// Assembles an [UCharArray] from parts (ostensibly, obtained through
/// [UCharArray::as_pascal_strings] above. Unsafe, as there is no guarantee
/// that the pointers are well-formed.
///
/// Takes ownership away from the pointers and strlens. Requires that
/// `len` is equal to the capacities and lengths of the vectors described by
/// `pointers` and `strlens`.
#[allow(dead_code)]
pub unsafe fn from_raw_parts(
pointers: *mut *mut sys::UChar,
strlens: *mut *mut i32,
len: usize,
) -> UCharArray {
let pointers_vec: Vec<*mut sys::UChar> = Vec::from_raw_parts(pointers, len, len);
let strlens_vec: Vec<i32> = Vec::from_raw_parts(strlens as *mut i32, len, len);
let elements = pointers_vec.into_iter().zip(strlens_vec);
let elements = elements
.map(|(ptr, len): (*mut sys::UChar, i32)| {
assert!(len >= 0);
let len_i32 = len as usize;
let raw: Vec<sys::UChar> = Vec::from_raw_parts(ptr, len_i32, len_i32);
ustring::UChar::from(raw)
})
.collect::<Vec<ustring::UChar>>();
let pointers = elements.iter().map(|e| e.as_c_ptr()).collect();
let strlens = elements.iter().map(|e| e.len() as i32).collect();
UCharArray {
elements,
pointers,
strlens,
}
}
}
#[cfg(test)]
mod testing {
use crate::*;
#[test]
fn test_pascal_strings() {
let array = UCharArray::try_from(&["eenie", "meenie", "minie", "moe"][..])
.expect("created with success");
let array_len = array.len();
let (strings, strlens, len) = unsafe { array.as_pascal_strings() };
assert_eq!(len, array_len);
let reconstructed = unsafe { UCharArray::from_raw_parts(strings, strlens, len) };
let result = reconstructed
.as_ref()
.iter()
.map(|e| String::try_from(e).expect("conversion is a success"))
.collect::<Vec<String>>();
assert_eq!(vec!["eenie", "meenie", "minie", "moe"], result);
}
#[test]
fn test_formatting() {
let array = ["eenie", "meenie", "minie", "moe"];
let formatter = crate::UListFormatter::try_new("en-US").expect("has list format");
let result = formatter.format(&array).expect("formatting succeeds");
assert_eq!("eenie, meenie, minie, and moe", result);
}
#[test]
fn test_formatting_sr() {
let array = ["Раја", "Гаја", "Влаја"]; // Huey, Dewey, and Louie.
let formatter = crate::UListFormatter::try_new("sr-RS").expect("has list format");
let result = formatter.format(&array).expect("formatting succeeds");
assert_eq!("Раја, Гаја и Влаја", result);
}
#[test]
#[cfg(feature = "icu_version_67_plus")]
fn test_formatting_styled() {
let array = ["Раја", "Гаја", "Влаја"];
let formatter = crate::UListFormatter::try_new_styled(
"sr-RS",
sys::UListFormatterType::ULISTFMT_TYPE_OR,
sys::UListFormatterWidth::ULISTFMT_WIDTH_WIDE,
)
.expect("has list format");
let result = formatter.format(&array).expect("formatting succeeds");
assert_eq!("Раја, Гаја или Влаја", result);
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_uchar/src/lib.rs | rust_icu_uchar/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ICU unicode character properties support
//!
//! NOTE: Only very partially supported. However, it is easy to add new
//! functionality, so if you want you can do that yourself, or you can report
//! missing functionality at <https://github.com/google/rust_icu/issues>.
//!
//! Since 1.0.2
use {
rust_icu_common as common,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
std::ffi,
};
/// Implements `u_charFromName`.
///
/// Since 1.0.2
pub fn from_name(name_choice: sys::UCharNameChoice, name: &str)
-> Result<sys::UChar32, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz = ffi::CString::new(name)?;
let result = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(u_charFromName)(name_choice, asciiz.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
Ok(result)
}
/// Implements `u_charType`.
///
/// Since 1.0.2
pub fn char_type(c: sys::UChar32) -> sys::UCharCategory {
let result = unsafe { versioned_function!(u_charType)(c) };
result.into()
}
/// See <http://www.unicode.org/reports/tr44/#Canonical_Combining_Class_Values> for
/// the list of combining class values.
///
/// Implements `u_getCombiningClass`
///
/// Since 1.0.2
pub fn get_combining_class(c: sys::UChar32) -> u8 {
unsafe { versioned_function!(u_getCombiningClass)(c) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_name() {
struct Test {
name_choice: sys::UCharNameChoice,
name: &'static str,
expected: sys::UChar32,
}
let tests = vec![
Test {
name_choice: sys::UCharNameChoice::U_UNICODE_CHAR_NAME,
name: "LATIN CAPITAL LETTER A",
expected: 'A' as sys::UChar32,
},
Test {
name_choice: sys::UCharNameChoice::U_UNICODE_CHAR_NAME,
name: "LATIN CAPITAL LETTER B",
expected: 'B' as sys::UChar32,
},
Test {
name_choice: sys::UCharNameChoice::U_UNICODE_CHAR_NAME,
name: "LATIN SMALL LETTER C",
expected: 'c' as sys::UChar32,
},
Test {
name_choice: sys::UCharNameChoice::U_UNICODE_CHAR_NAME,
name: "CJK RADICAL BOX",
expected: '⺆' as sys::UChar32,
},
];
for test in tests {
let result = from_name(test.name_choice, test.name).unwrap();
assert_eq!(result, test.expected);
}
}
#[test]
fn test_char_type() {
struct Test {
ch: sys::UChar32,
cat: sys::UCharCategory,
}
let tests = vec![
Test {
ch: 'A' as sys::UChar32,
cat: sys::UCharCategory::U_UPPERCASE_LETTER,
},
Test {
ch: 0x300, // A combining character.
cat: sys::UCharCategory::U_NON_SPACING_MARK,
},
];
for test in tests {
let result = char_type(test.ch);
assert_eq!(result, test.cat);
}
}
#[test]
fn test_combining_class() {
#[derive(Debug)]
struct Test {
ch: sys::UChar32,
class: u8,
}
let tests = vec![
Test {
ch: 'A' as sys::UChar32,
class: 0,
},
Test {
ch: 0x300 as sys::UChar32,
class: 230,
},
Test {
ch: 0x301 as sys::UChar32,
class: 230,
},
];
for test in tests {
let result = get_combining_class(test.ch);
assert_eq!(result, test.class, "test: {:?}", test);
}
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu/src/lib.rs | rust_icu/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Rust bindings for the ICU library
//!
//! The [ICU](http://site.icu-project.org/home) library is a C, C++ and Java library providing
//! Unicode functionality. This crate makes the ICU functionality available to programs in rust.
//!
//! This top level crate serves two purposes:
//!
//! 1. Makes all ICU functionality providing crates available through a single
//! import.
//! 2. Provides a unified namespace for all of this functionality to live in.
//!
//! The crate makes the following reexports:
//!
//! | Original | Remapped |
//! | -------- | -------- |
//! | rust_icu_common | icu::common |
//! | rust_icu_sys | icu::sys |
//! | rust_icu_ubrk | brk |
//! | rust_icu_ucal | icu::cal |
//! | rust_icu_ucol | icu::col |
//! | rust_icu_udat | icu::dat |
//! | rust_icu_udata | icu::data |
//! | rust_icu_uenum | icu::enums |
//! | rust_icu_ulistformatter | icu::listformatter |
//! | rust_icu_uloc | icu::loc |
//! | rust_icu_umsg | icu::msg |
//! | rust_icu_unorm | unorm |
//! | rust_icu_ustring | icu::string |
//! | rust_icu_utext | text |
//! | rust_icu_utrans | trans |
pub use rust_icu_common as common;
pub use rust_icu_sys as sys;
pub use rust_icu_ubrk as brk;
pub use rust_icu_ucal as cal;
pub use rust_icu_ucol as col;
pub use rust_icu_udat as dat;
pub use rust_icu_udata as data;
pub use rust_icu_uenum as enums;
pub use rust_icu_ulistformatter as listformatter;
pub use rust_icu_uloc as loc;
pub use rust_icu_umsg as msg;
pub use rust_icu_ustring as string;
pub use rust_icu_utext as text;
pub use rust_icu_utrans as trans;
pub use rust_icu_unorm2 as norm;
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_unorm2/src/lib.rs | rust_icu_unorm2/src/lib.rs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Contains implementations of functions from ICU's `unorm2.h`.
use {
rust_icu_common as common,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_ustring as ustring,
rust_icu_ustring::buffered_uchar_method_with_retry,
};
use std::convert::{TryFrom, TryInto};
#[derive(Debug)]
pub struct UNormalizer {
rep: std::ptr::NonNull<sys::UNormalizer2>,
owned: bool,
}
impl Drop for UNormalizer {
/// Implements `unorm2_close`
fn drop(&mut self) {
// Close the normalizer only if we own it.
if !self.owned {
return
}
unsafe {
versioned_function!(unorm2_close)(self.rep.as_ptr())
}
}
}
impl UNormalizer {
/// Implements `unorm2_getNFCInstance`.
pub fn new_nfc() -> Result<Self, common::Error> {
unsafe { UNormalizer::new_normalizer_unowned(versioned_function!(unorm2_getNFCInstance)) }
}
/// Implements `unorm2_getNFDInstance`.
pub fn new_nfd() -> Result<Self, common::Error> {
unsafe { UNormalizer::new_normalizer_unowned(versioned_function!(unorm2_getNFDInstance)) }
}
/// Implements `unorm2_getNFKCInstance`.
pub fn new_nfkc() -> Result<Self, common::Error> {
unsafe { UNormalizer::new_normalizer_unowned(versioned_function!(unorm2_getNFKCInstance)) }
}
/// Implements `unorm2_getNFKDInstance`.
pub fn new_nfkd() -> Result<Self, common::Error> {
unsafe { UNormalizer::new_normalizer_unowned(versioned_function!(unorm2_getNFKDInstance)) }
}
/// Implements `unorm2_getNFKCCasefoldInstance`.
pub fn new_nfkc_casefold() -> Result<Self, common::Error> {
unsafe { UNormalizer::new_normalizer_unowned(versioned_function!(unorm2_getNFKCCasefoldInstance)) }
}
unsafe fn new_normalizer_unowned(
constrfn: unsafe extern "C" fn(*mut sys::UErrorCode) -> *const sys::UNormalizer2) -> Result<Self, common::Error> {
let mut status = common::Error::OK_CODE;
let rep = {
assert!(common::Error::is_ok(status));
let ptr = constrfn(&mut status) as *mut sys::UNormalizer2;
std::ptr::NonNull::new_unchecked(ptr)
};
common::Error::ok_or_warning(status)?;
Ok(UNormalizer{ rep, owned: false })
}
/// Implements `unorm2_normalize`.
pub fn normalize(&self, norm: &str) -> Result<String, common::Error> {
let norm = ustring::UChar::try_from(norm)?;
let result = self.normalize_ustring(&norm)?;
String::try_from(&result)
}
/// Implements `unorm2_normalize`.
pub fn normalize_ustring(
&self,
norm: &ustring::UChar
) -> Result<ustring::UChar, common::Error> {
const CAPACITY: usize = 200;
buffered_uchar_method_with_retry!(
norm_uchar,
CAPACITY,
[ptr: *const sys::UNormalizer2, s: *const sys::UChar, l: i32,],
[]
);
let result = norm_uchar(
versioned_function!(unorm2_normalize),
self.rep.as_ptr(),
norm.as_c_ptr(),
norm.len() as i32,
)?;
Ok(result)
}
/// Implements `unorm2_composePair`.
pub fn compose_pair(&self, point1: sys::UChar32, point2: sys::UChar32) -> sys::UChar32 {
let result: sys::UChar32 = unsafe {
versioned_function!(unorm2_composePair)(
self.rep.as_ptr(), point1, point2)
};
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use rust_icu_ustring::UChar;
#[test]
fn test_compose_pair_nfkc() -> Result<(), common::Error> {
struct Test {
p1: sys::UChar32,
p2: sys::UChar32,
ex: sys::UChar32,
}
let tests = vec![
Test {p1: 1, p2: 0, ex: -1, },
// See the article: https://en.wikipedia.org/wiki/Combining_character
// LATIN CAPITAL LETTER A WITH GRAVE
Test {p2: 0x300, p1: 'A' as sys::UChar32, ex: 'À' as sys::UChar32 },
// LATIN CAPITAL LETTER A WITH ACUTE
Test {p2: 0x301, p1: 'A' as sys::UChar32, ex: 'Á' as sys::UChar32 },
// LATIN CAPITAL LETTER A WITH CIRCUMFLEX
Test {p2: 0x302, p1: 'A' as sys::UChar32, ex: 'Â' as sys::UChar32 },
// LATIN CAPITAL LETTER A WITH TILDE
Test {p2: 0x303, p1: 'A' as sys::UChar32, ex: 'Ã' as sys::UChar32 },
];
for t in tests {
let n = UNormalizer::new_nfkc()?;
let result = n.compose_pair(t.p1, t.p2);
assert_eq!(result, t.ex);
}
Ok(())
}
// https://github.com/google/rust_icu/issues/244
#[test]
fn test_long_input_string() -> Result<(), common::Error> {
let s = (0..67).map(|_| "탐").collect::<String>();
let u = UChar::try_from(&s[..]).unwrap();
let normalizer = UNormalizer::new_nfd().unwrap();
normalizer.normalize_ustring(&u).unwrap();
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_uloc/build.rs | rust_icu_uloc/build.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! See LICENSE for licensing information.
//!
//! This build.rs script provides Cargo _features_ indicating the target ICU4C library version,
//! enabling some conditionally compiled Rust code in this crate that depends on the particular
//! ICU4C version.
//!
//! Please refer to README.md for instructions on how to build the library for your use.
#[cfg(feature = "icu_config")]
fn main() -> anyhow::Result<()> {
use rust_icu_release::run;
run()
}
/// No-op if icu_config is disabled.
#[cfg(not(feature = "icu_config"))]
fn main() {}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_uloc/src/lib.rs | rust_icu_uloc/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use {
anyhow::anyhow,
rust_icu_common as common,
rust_icu_common::buffered_string_method_with_retry,
rust_icu_sys as sys,
rust_icu_sys::versioned_function,
rust_icu_sys::*,
rust_icu_uenum::Enumeration,
rust_icu_ustring as ustring,
rust_icu_ustring::buffered_uchar_method_with_retry,
std::{
cmp::Ordering,
collections::HashMap,
convert::{From, TryFrom, TryInto},
ffi, fmt,
os::raw,
},
};
/// Maximum length of locale supported by uloc.h.
/// See `ULOC_FULLNAME_CAPACITY`.
const LOCALE_CAPACITY: usize = 158;
/// [ULocMut] is a mutable companion to [ULoc].
///
/// It has methods that allow one to create a different [ULoc] by adding and
/// removing keywords to the locale identifier. You can only create a `ULocMut`
/// by converting from an existing `ULoc` by calling `ULocMut::from`. And once
/// you are done changing it, you can only convert it back with `ULoc::from`.
///
/// [ULocMut] is not meant to have comprehensive coverage of mutation options.
/// They may be added as necessary.
#[derive(Debug, Clone)]
pub struct ULocMut {
base: ULoc,
unicode_keyvalues: HashMap<String, String>,
other_keyvalues: HashMap<String, String>,
}
impl From<ULoc> for ULocMut {
/// Turns [ULoc] into [ULocMut], which can be mutated.
fn from(l: ULoc) -> Self {
let all_keywords = l.keywords();
let mut unicode_keyvalues: HashMap<String, String> = HashMap::new();
let mut other_keyvalues: HashMap<String, String> = HashMap::new();
for kw in all_keywords {
// Despite the many unwraps below, none should be triggered, since we know
// that the keywords come from the list of keywords that already exist.
let ukw = to_unicode_locale_key(&kw);
match ukw {
None => {
let v = l.keyword_value(&kw).unwrap().unwrap();
other_keyvalues.insert(kw, v);
}
Some(u) => {
let v = l.unicode_keyword_value(&u).unwrap().unwrap();
unicode_keyvalues.insert(u, v);
}
}
}
// base_name may return an invalid language tag, so convert here.
let locmut = ULocMut {
base: l.base_name(),
unicode_keyvalues,
other_keyvalues,
};
locmut
}
}
impl From<ULocMut> for ULoc {
// Creates an [ULoc] from [ULocMut].
fn from(lm: ULocMut) -> Self {
// Assemble the unicode extension.
let mut unicode_extensions_vec = lm
.unicode_keyvalues
.iter()
.map(|(k, v)| format!("{}-{}", k, v))
.collect::<Vec<String>>();
unicode_extensions_vec.sort();
let unicode_extensions: String = unicode_extensions_vec
.join("-");
let unicode_extension: String = if unicode_extensions.len() > 0 {
vec!["u-".to_string(), unicode_extensions]
.into_iter()
.collect()
} else {
"".to_string()
};
// Assemble all other extensions.
let mut all_extensions: Vec<String> = lm
.other_keyvalues
.iter()
.map(|(k, v)| format!("{}-{}", k, v))
.collect();
if unicode_extension.len() > 0 {
all_extensions.push(unicode_extension);
}
// The base language must be in the form of BCP47 language tag to
// be usable in the code below.
let base_tag = lm.base.to_language_tag(true)
.expect("should be known-good");
let mut everything_vec: Vec<String> = vec![base_tag];
if !all_extensions.is_empty() {
all_extensions.sort();
let extension_string = all_extensions.join("-");
everything_vec.push(extension_string);
}
let everything = everything_vec.join("-").to_lowercase();
ULoc::for_language_tag(&everything).unwrap()
}
}
impl ULocMut {
/// Sets the specified unicode extension keyvalue. Only valid keys can be set,
/// inserting an invalid extension key does not change [ULocMut].
pub fn set_unicode_keyvalue(&mut self, key: &str, value: &str) -> Option<String> {
if let None = to_unicode_locale_key(key) {
return None;
}
self.unicode_keyvalues
.insert(key.to_string(), value.to_string())
}
/// Removes the specified unicode extension keyvalue. Only valid keys can
/// be removed, attempting to remove an invalid extension key does not
/// change [ULocMut].
pub fn remove_unicode_keyvalue(&mut self, key: &str) -> Option<String> {
if let None = to_unicode_locale_key(key) {
return None;
}
self.unicode_keyvalues.remove(key)
}
}
/// A representation of a Unicode locale.
///
/// For the time being, only basic conversion and methods are in fact implemented.
///
/// To get basic validation when creating a locale, use
/// [`for_language_tag`](ULoc::for_language_tag) with a Unicode BCP-47 locale ID.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct ULoc {
// A locale's representation in C is really just a string.
repr: String,
}
/// Implement the Display trait to convert the ULoc into string for display.
///
/// The string for display and string serialization happen to be the same for [ULoc].
impl fmt::Display for ULoc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.repr)
}
}
impl TryFrom<&str> for ULoc {
type Error = common::Error;
/// Creates a new ULoc from a string slice.
///
/// The creation wil fail if the locale is nonexistent.
fn try_from(s: &str) -> Result<Self, Self::Error> {
let s = String::from(s);
ULoc { repr: s }.canonicalize()
}
}
impl TryFrom<&ffi::CStr> for ULoc {
type Error = common::Error;
/// Creates a new `ULoc` from a borrowed C string.
fn try_from(s: &ffi::CStr) -> Result<Self, Self::Error> {
let repr = s.to_str()?;
ULoc {
repr: String::from(repr),
}
.canonicalize()
}
}
impl ULoc {
/// Implements `uloc_getLanguage`.
pub fn language(&self) -> Option<String> {
self.call_buffered_string_method_to_option(versioned_function!(uloc_getLanguage))
}
/// Implements `uloc_getScript`.
pub fn script(&self) -> Option<String> {
self.call_buffered_string_method_to_option(versioned_function!(uloc_getScript))
}
/// Implements `uloc_getCountry`.
pub fn country(&self) -> Option<String> {
self.call_buffered_string_method_to_option(versioned_function!(uloc_getCountry))
}
/// Implements `uloc_getVariant`.
pub fn variant(&self) -> Option<String> {
self.call_buffered_string_method_to_option(versioned_function!(uloc_getVariant))
}
/// Implements `uloc_getName`.
pub fn name(&self) -> Option<String> {
self.call_buffered_string_method_to_option(versioned_function!(uloc_getName))
}
/// Implements `uloc_canonicalize` from ICU4C.
pub fn canonicalize(&self) -> Result<ULoc, common::Error> {
self.call_buffered_string_method(versioned_function!(uloc_canonicalize))
.map(|repr| ULoc { repr })
}
/// Implements 'uloc_getISO3Language' from ICU4C.
pub fn iso3_language(&self) -> Option<String> {
let lang = unsafe {
ffi::CStr::from_ptr(
versioned_function!(uloc_getISO3Language)(self.as_c_str().as_ptr())
).to_str()
};
let value = lang.unwrap();
if value.is_empty() {
None
} else {
Some(value.to_string())
}
}
/// Implements 'uloc_getISO3Country' from ICU4C.
pub fn iso3_country(&self) -> Option<String> {
let country = unsafe {
ffi::CStr::from_ptr(
versioned_function!(uloc_getISO3Country)(self.as_c_str().as_ptr())
).to_str()
};
let value = country.unwrap();
if value.is_empty() {
None
} else {
Some(value.to_string())
}
}
/// Implements `uloc_getDisplayLanguage`.
pub fn display_language(&self, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_language_impl,
LOCALE_CAPACITY,
[locale: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
display_language_impl(
versioned_function!(uloc_getDisplayLanguage),
self.as_c_str().as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayScript`.
pub fn display_script(&self, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_script_impl,
LOCALE_CAPACITY,
[locale: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
display_script_impl(
versioned_function!(uloc_getDisplayScript),
self.as_c_str().as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayCountry`.
pub fn display_country(&self, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_country_impl,
LOCALE_CAPACITY,
[locale: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
display_country_impl(
versioned_function!(uloc_getDisplayCountry),
self.as_c_str().as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayVariant`.
pub fn display_variant(&self, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_variant_impl,
LOCALE_CAPACITY,
[locale: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
display_variant_impl(
versioned_function!(uloc_getDisplayCountry),
self.as_c_str().as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayKeyword`.
pub fn display_keyword(keyword: &String, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_keyword_impl,
LOCALE_CAPACITY,
[keyword: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
let keyword = ffi::CString::new(keyword.as_str()).unwrap();
display_keyword_impl(
versioned_function!(uloc_getDisplayKeyword),
keyword.as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayKeywordValue`.
pub fn display_keyword_value(&self, keyword: &String, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_keyword_value_impl,
LOCALE_CAPACITY,
[keyword: *const raw::c_char, value: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
let keyword = ffi::CString::new(keyword.as_str()).unwrap();
display_keyword_value_impl(
versioned_function!(uloc_getDisplayKeywordValue),
self.as_c_str().as_ptr(),
keyword.as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_getDisplayName`.
pub fn display_name(&self, display_locale: &ULoc) -> Result<ustring::UChar, common::Error> {
buffered_uchar_method_with_retry!(
display_name_impl,
LOCALE_CAPACITY,
[locale: *const raw::c_char, display_locale: *const raw::c_char,],
[]
);
display_name_impl(
versioned_function!(uloc_getDisplayName),
self.as_c_str().as_ptr(),
display_locale.as_c_str().as_ptr(),
)
}
/// Implements `uloc_countAvailable`.
pub fn count_available() -> i32 {
let count = unsafe { versioned_function!(uloc_countAvailable)() };
count
}
/// Implements `uloc_getAvailable`.
pub fn get_available(n: i32) -> Result<ULoc, common::Error> {
if (0 > n) || (n >= Self::count_available()) {
panic!("{} is negative or greater than or equal to the value returned from count_available()", n);
}
let ptr = unsafe { versioned_function!(uloc_getAvailable)(n) };
if ptr == std::ptr::null() {
return Err(common::Error::Wrapper(anyhow!("uloc_getAvailable() returned a null pointer")));
}
let label = unsafe { ffi::CStr::from_ptr(ptr).to_str().unwrap() };
ULoc::try_from(label)
}
/// Returns a vector of available locales
pub fn get_available_locales() -> Vec<ULoc> {
let count = ULoc::count_available();
let mut vec = Vec::with_capacity(count as usize);
let mut index: i32 = 0;
while index < count {
let locale = Self::get_available(index).unwrap();
vec.push(locale);
index += 1;
}
vec
}
/// Implements `uloc_openAvailableByType`.
#[cfg(feature = "icu_version_67_plus")]
pub fn open_available_by_type(locale_type: ULocAvailableType) -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
unsafe {
let iter = Enumeration::from_raw_parts(None, versioned_function!(uloc_openAvailableByType)(locale_type, &mut status));
common::Error::ok_or_warning(status)?;
Ok(iter)
}
}
/// Returns a vector of locales of the requested type.
#[cfg(feature = "icu_version_67_plus")]
pub fn get_available_locales_by_type(locale_type: ULocAvailableType) -> Vec<ULoc> {
if locale_type == ULocAvailableType::ULOC_AVAILABLE_COUNT {
panic!("ULOC_AVAILABLE_COUNT is for internal use only");
}
Self::open_available_by_type(locale_type).unwrap().map(|x| ULoc::try_from(x.unwrap().as_str()).unwrap()).collect()
}
/// Implements `uloc_addLikelySubtags` from ICU4C.
pub fn add_likely_subtags(&self) -> Result<ULoc, common::Error> {
self.call_buffered_string_method(versioned_function!(uloc_addLikelySubtags))
.map(|repr| ULoc { repr })
}
/// Implements `uloc_minimizeSubtags` from ICU4C.
pub fn minimize_subtags(&self) -> Result<ULoc, common::Error> {
self.call_buffered_string_method(versioned_function!(uloc_minimizeSubtags))
.map(|repr| ULoc { repr })
}
/// Implements `uloc_toLanguageTag` from ICU4C.
pub fn to_language_tag(&self, strict: bool) -> Result<String, common::Error> {
let locale_id = self.as_c_str();
// No `UBool` constants available in rust_icu_sys, unfortunately.
let strict = if strict { 1 } else { 0 };
buffered_string_method_with_retry(
|buf, len, error| unsafe {
versioned_function!(uloc_toLanguageTag)(
locale_id.as_ptr(),
buf,
len,
strict,
error,
)
},
LOCALE_CAPACITY,
)
}
pub fn open_keywords(&self) -> Result<Enumeration, common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz_locale = self.as_c_str();
let raw_enum = unsafe {
assert!(common::Error::is_ok(status));
versioned_function!(uloc_openKeywords)(asciiz_locale.as_ptr(), &mut status)
};
common::Error::ok_or_warning(status)?;
// "No error but null" means that there are no keywords
if raw_enum.is_null() {
Ok(Enumeration::empty())
} else {
Ok(unsafe { Enumeration::from_raw_parts(None, raw_enum) })
}
}
/// Implements `uloc_openKeywords()` from ICU4C.
pub fn keywords(&self) -> impl Iterator<Item = String> {
self.open_keywords()
.unwrap()
.map(|result| result.unwrap())
}
/// Implements `icu::Locale::getUnicodeKeywords()` from the C++ API.
pub fn unicode_keywords(&self) -> impl Iterator<Item = String> {
self.keywords().filter_map(|s| to_unicode_locale_key(&s))
}
/// Implements `uloc_getKeywordValue()` from ICU4C.
pub fn keyword_value(&self, keyword: &str) -> Result<Option<String>, common::Error> {
let locale_id = self.as_c_str();
let keyword_name = str_to_cstring(keyword);
buffered_string_method_with_retry(
|buf, len, error| unsafe {
versioned_function!(uloc_getKeywordValue)(
locale_id.as_ptr(),
keyword_name.as_ptr(),
buf,
len,
error,
)
},
LOCALE_CAPACITY,
)
.map(|value| if value.is_empty() { None } else { Some(value) })
}
/// Implements `icu::Locale::getUnicodeKeywordValue()` from the C++ API.
pub fn unicode_keyword_value(
&self,
unicode_keyword: &str,
) -> Result<Option<String>, common::Error> {
let legacy_keyword = to_legacy_key(unicode_keyword);
match legacy_keyword {
Some(legacy_keyword) => match self.keyword_value(&legacy_keyword) {
Ok(Some(legacy_value)) => {
Ok(to_unicode_locale_type(&legacy_keyword, &legacy_value))
}
Ok(None) => Ok(None),
Err(e) => Err(e),
},
None => Ok(None),
}
}
/// Returns the current label of this locale.
pub fn label(&self) -> &str {
&self.repr
}
/// Returns the current locale name as a C string.
pub fn as_c_str(&self) -> ffi::CString {
ffi::CString::new(self.repr.clone()).expect("ULoc contained interior NUL bytes")
}
/// Implements `uloc_forLanguageTag` from ICU4C.
///
/// Note that an invalid tag will cause that tag and all others to be
/// ignored. For example `en-us` will work but `en_US` will not.
pub fn for_language_tag(tag: &str) -> Result<ULoc, common::Error> {
let tag = str_to_cstring(tag);
let locale_id = buffered_string_method_with_retry(
|buf, len, error| unsafe {
versioned_function!(uloc_forLanguageTag)(
tag.as_ptr(),
buf,
len,
std::ptr::null_mut(),
error
)
},
LOCALE_CAPACITY,
)?;
ULoc::try_from(&locale_id[..])
}
/// Call a `uloc` method that takes this locale's ID and returns a string.
fn call_buffered_string_method(
&self,
uloc_method: unsafe extern "C" fn(
*const raw::c_char,
*mut raw::c_char,
i32,
*mut UErrorCode,
) -> i32,
) -> Result<String, common::Error> {
let asciiz = self.as_c_str();
buffered_string_method_with_retry(
|buf, len, error| unsafe { uloc_method(asciiz.as_ptr(), buf, len, error) },
LOCALE_CAPACITY,
)
}
/// Call a `uloc` method that takes this locale's ID, panics on any errors, and returns
/// `Some(result)` if the resulting string is non-empty, or `None` otherwise.
fn call_buffered_string_method_to_option(
&self,
uloc_method: unsafe extern "C" fn(
*const raw::c_char,
*mut raw::c_char,
i32,
*mut UErrorCode,
) -> i32,
) -> Option<String> {
let value: String = self.call_buffered_string_method(uloc_method).unwrap();
if value.is_empty() {
None
} else {
Some(value)
}
}
/// Implements `uloc_getBaseName` from ICU4C.
pub fn base_name(self) -> Self {
let result = self
.call_buffered_string_method(versioned_function!(uloc_getBaseName))
.expect("should be able to produce a shorter locale");
ULoc::try_from(&result[..]).expect("should be able to convert to locale")
}
}
/// This implementation is based on ULocale.compareTo from ICU4J.
/// See
/// <https://github.com/unicode-org/icu/blob/%6d%61%73%74%65%72/icu4j/main/classes/core/src/com/ibm/icu/util/ULocale.java>
impl Ord for ULoc {
fn cmp(&self, other: &Self) -> Ordering {
/// Compare corresponding keywords from two `ULoc`s. If the keywords match, compare the
/// keyword values.
fn compare_keywords(
this: &ULoc,
self_keyword: &Option<String>,
other: &ULoc,
other_keyword: &Option<String>,
) -> Option<Ordering> {
match (self_keyword, other_keyword) {
(Some(self_keyword), Some(other_keyword)) => {
// Compare the two keywords
match self_keyword.cmp(&other_keyword) {
Ordering::Equal => {
// Compare the two keyword values
let self_val = this.keyword_value(&self_keyword[..]).unwrap();
let other_val = other.keyword_value(&other_keyword[..]).unwrap();
Some(self_val.cmp(&other_val))
}
unequal_ordering => Some(unequal_ordering),
}
}
// `other` has run out of keywords
(Some(_), _) => Some(Ordering::Greater),
// `this` has run out of keywords
(_, Some(_)) => Some(Ordering::Less),
// Both iterators have run out
(_, _) => None,
}
}
self.language()
.cmp(&other.language())
.then_with(|| self.script().cmp(&other.script()))
.then_with(|| self.country().cmp(&other.country()))
.then_with(|| self.variant().cmp(&other.variant()))
.then_with(|| {
let mut self_keywords = self.keywords();
let mut other_keywords = other.keywords();
while let Some(keyword_ordering) =
compare_keywords(self, &self_keywords.next(), other, &other_keywords.next())
{
match keyword_ordering {
Ordering::Equal => {}
unequal_ordering => {
return unequal_ordering;
}
}
}
// All keywords and values were identical (or there were none)
Ordering::Equal
})
}
}
impl PartialOrd for ULoc {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// Gets the current system default locale.
///
/// Implements `uloc_getDefault` from ICU4C.
pub fn get_default() -> ULoc {
let loc = unsafe { versioned_function!(uloc_getDefault)() };
let uloc_cstr = unsafe { ffi::CStr::from_ptr(loc) };
crate::ULoc::try_from(uloc_cstr).expect("could not convert default locale to ULoc")
}
/// Sets the current default system locale.
///
/// Implements `uloc_setDefault` from ICU4C.
pub fn set_default(loc: &ULoc) -> Result<(), common::Error> {
let mut status = common::Error::OK_CODE;
let asciiz = str_to_cstring(&loc.repr);
unsafe { versioned_function!(uloc_setDefault)(asciiz.as_ptr(), &mut status) };
common::Error::ok_or_warning(status)
}
/// Implements `uloc_acceptLanguage` from ICU4C.
pub fn accept_language(
accept_list: impl IntoIterator<Item = impl Into<ULoc>>,
available_locales: impl IntoIterator<Item = impl Into<ULoc>>,
) -> Result<(Option<ULoc>, UAcceptResult), common::Error> {
let mut accept_result: UAcceptResult = UAcceptResult::ULOC_ACCEPT_FAILED;
let mut accept_list_cstrings: Vec<ffi::CString> = vec![];
// This is mutable only to satisfy the missing `const`s in the ICU4C API.
let mut accept_list: Vec<*const raw::c_char> = accept_list
.into_iter()
.map(|item| {
let uloc: ULoc = item.into();
accept_list_cstrings.push(uloc.as_c_str());
accept_list_cstrings
.last()
.expect("non-empty list")
.as_ptr()
})
.collect();
let available_locales: Vec<ULoc> = available_locales
.into_iter()
.map(|item| item.into())
.collect();
let available_locales: Vec<&str> = available_locales.iter().map(|uloc| uloc.label()).collect();
let mut available_locales = Enumeration::try_from(&available_locales[..])?;
let matched_locale = buffered_string_method_with_retry(
|buf, len, error| unsafe {
versioned_function!(uloc_acceptLanguage)(
buf,
len,
&mut accept_result,
accept_list.as_mut_ptr(),
accept_list.len() as i32,
available_locales.repr(),
error,
)
},
LOCALE_CAPACITY,
);
// Having no match is a valid if disappointing result.
if accept_result == UAcceptResult::ULOC_ACCEPT_FAILED {
return Ok((None, accept_result));
}
matched_locale
.and_then(|s| ULoc::try_from(s.as_str()))
.map(|uloc| (Some(uloc), accept_result))
}
/// Implements `uloc_toUnicodeLocaleKey` from ICU4C.
pub fn to_unicode_locale_key(legacy_keyword: &str) -> Option<String> {
let legacy_keyword = str_to_cstring(legacy_keyword);
let unicode_keyword: Option<ffi::CString> = unsafe {
let ptr = versioned_function!(uloc_toUnicodeLocaleKey)(legacy_keyword.as_ptr());
ptr.as_ref().map(|ptr| ffi::CStr::from_ptr(ptr).to_owned())
};
unicode_keyword.map(|cstring| cstring_to_string(&cstring))
}
/// Implements `uloc_toUnicodeLocaleType` from ICU4C.
pub fn to_unicode_locale_type(legacy_keyword: &str, legacy_value: &str) -> Option<String> {
let legacy_keyword = str_to_cstring(legacy_keyword);
let legacy_value = str_to_cstring(legacy_value);
let unicode_value: Option<ffi::CString> = unsafe {
let ptr = versioned_function!(uloc_toUnicodeLocaleType)(
legacy_keyword.as_ptr(),
legacy_value.as_ptr(),
);
ptr.as_ref().map(|ptr| ffi::CStr::from_ptr(ptr).to_owned())
};
unicode_value.map(|cstring| cstring_to_string(&cstring))
}
/// Implements `uloc_toLegacyKey` from ICU4C.
pub fn to_legacy_key(unicode_keyword: &str) -> Option<String> {
let unicode_keyword = str_to_cstring(unicode_keyword);
let legacy_keyword: Option<ffi::CString> = unsafe {
let ptr = versioned_function!(uloc_toLegacyKey)(unicode_keyword.as_ptr());
ptr.as_ref().map(|ptr| ffi::CStr::from_ptr(ptr).to_owned())
};
legacy_keyword.map(|cstring| cstring_to_string(&cstring))
}
/// Infallibly converts a Rust string to a `CString`. If there's an interior NUL, the string is
/// truncated up to that point.
fn str_to_cstring(input: &str) -> ffi::CString {
ffi::CString::new(input)
.unwrap_or_else(|e| ffi::CString::new(&input[0..e.nul_position()]).unwrap())
}
/// Infallibly converts a `CString` to a Rust `String`. We can safely assume that any strings
/// coming from ICU data are valid UTF-8.
fn cstring_to_string(input: &ffi::CString) -> String {
input.to_string_lossy().to_string()
}
#[cfg(test)]
mod tests {
use {super::*, anyhow::Error};
#[test]
fn test_language() -> Result<(), Error> {
let loc = ULoc::try_from("es-CO")?;
assert_eq!(loc.language(), Some("es".to_string()));
Ok(())
}
#[test]
fn test_language_absent() -> Result<(), Error> {
let loc = ULoc::for_language_tag("und-CO")?;
assert_eq!(loc.language(), None);
Ok(())
}
// https://github.com/google/rust_icu/issues/244
#[test]
fn test_long_language_tag() -> Result<(), Error> {
let mut language_tag: String = "und-CO".to_owned();
let language_tag_rest = (0..500).map(|_| " ").collect::<String>();
language_tag.push_str(&language_tag_rest);
let _loc = ULoc::for_language_tag(&language_tag)?;
Ok(())
}
#[test]
fn test_script() -> Result<(), Error> {
let loc = ULoc::try_from("sr-Cyrl")?;
assert_eq!(loc.script(), Some("Cyrl".to_string()));
Ok(())
}
#[test]
fn test_script_absent() -> Result<(), Error> {
let loc = ULoc::try_from("sr")?;
assert_eq!(loc.script(), None);
Ok(())
}
#[test]
fn test_country() -> Result<(), Error> {
let loc = ULoc::try_from("es-CO")?;
assert_eq!(loc.country(), Some("CO".to_string()));
Ok(())
}
#[test]
fn test_country_absent() -> Result<(), Error> {
let loc = ULoc::try_from("es")?;
assert_eq!(loc.country(), None);
Ok(())
}
// This test yields a different result in ICU versions prior to 64:
// "zh-Latn@collation=pinyin".
#[cfg(feature = "icu_version_64_plus")]
#[test]
fn test_variant() -> Result<(), Error> {
let loc = ULoc::try_from("zh-Latn-pinyin")?;
assert_eq!(
loc.variant(),
Some("PINYIN".to_string()),
"locale was: {:?}",
loc
);
Ok(())
}
#[test]
fn test_variant_absent() -> Result<(), Error> {
let loc = ULoc::try_from("zh-Latn")?;
assert_eq!(loc.variant(), None);
Ok(())
}
#[cfg(feature = "icu_version_64_plus")]
#[test]
fn test_name() -> Result<(), Error> {
let loc = ULoc::try_from("en-US")?;
match loc.name() {
None => assert!(false),
Some(name) => assert_eq!(name, "en_US"),
}
let loc = ULoc::try_from("und")?;
assert_eq!(loc.name(), None);
let loc = ULoc::try_from("")?;
assert_eq!(loc.name(), None);
Ok(())
}
#[test]
fn test_default_locale() {
let loc = ULoc::try_from("fr-fr").expect("get fr_FR locale");
set_default(&loc).expect("successful set of locale");
assert_eq!(get_default().label(), loc.label());
assert_eq!(loc.label(), "fr_FR", "The locale should get canonicalized");
let loc = ULoc::try_from("en-us").expect("get en_US locale");
set_default(&loc).expect("successful set of locale");
assert_eq!(get_default().label(), loc.label());
}
#[test]
fn test_add_likely_subtags() {
let loc = ULoc::try_from("en-US").expect("get en_US locale");
let with_likely_subtags = loc.add_likely_subtags().expect("should add likely subtags");
let expected = ULoc::try_from("en_Latn_US").expect("get en_Latn_US locale");
assert_eq!(with_likely_subtags.label(), expected.label());
}
#[test]
fn test_minimize_subtags() {
let loc = ULoc::try_from("sr_Cyrl_RS").expect("get sr_Cyrl_RS locale");
let minimized_subtags = loc.minimize_subtags().expect("should minimize subtags");
let expected = ULoc::try_from("sr").expect("get sr locale");
assert_eq!(minimized_subtags.label(), expected.label());
}
#[test]
fn test_to_language_tag() {
let loc = ULoc::try_from("sr_Cyrl_RS").expect("get sr_Cyrl_RS locale");
let language_tag = loc
.to_language_tag(true)
.expect("should convert to language tag");
assert_eq!(language_tag, "sr-Cyrl-RS".to_string());
}
#[test]
fn test_keywords() -> Result<(), Error> {
let loc = ULoc::for_language_tag("az-Cyrl-AZ-u-ca-hebrew-fw-sunday-nu-deva-tz-usnyc")?;
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/build.rs | rust_icu_sys/build.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// See LICENSE for licensing information.
//
// This build.rs script tries to generate low-level rust bindings for the current ICU library.
// Please refer to README.md for instructions on how to build the library for
// your use.
/// This is all a no-op if `use-bindgen` disabled.
#[cfg(feature = "use-bindgen")]
mod inner {
use {
anyhow::{Context, Ok, Result},
bindgen,
lazy_static::lazy_static,
std::env,
std::fs::File,
std::io::Write,
std::path::Path,
};
use rust_icu_release::ICUConfig;
lazy_static! {
// The modules for which bindings will be generated. Add more if you need them. The list
// should be topologicaly sorted based on the inclusion relationship between the respective
// headers. Any of these will fail if the required binaries are not present in $PATH.
static ref BINDGEN_SOURCE_MODULES: Vec<&'static str> = vec![
"ubrk",
"ucal",
"uclean",
"ucnv",
"ucol",
"ucsdet",
"udat",
"udatpg",
"udata",
"uenum",
"ufieldpositer",
"uformattable",
"ulistformatter",
"umisc",
"umsg",
"unum",
"unumberformatter",
"upluralrules",
"uset",
"ustring",
"utext",
"utrans",
"unorm2",
"ucptrie",
"umutablecptrie",
];
// C functions that will be made available to rust code. Add more to this list if you want to
// bring in more types.
static ref BINDGEN_ALLOWLIST_FUNCTIONS: Vec<&'static str> = vec![
"u_.*",
"ubrk_.*",
"ucal_.*",
"ucnv_.*",
"ucol_.*",
"ucsdet_.*",
"udat_.*",
"udatpg_.*",
"udata_.*",
"uenum_.*",
"ufieldpositer_.*",
"ufmt_.*",
"ulistfmt_.*",
"uloc_.*",
"umsg_.*",
"unum_.*",
"unumf_.*",
"uplrules_.*",
"utext_.*",
"utrans_.*",
"unorm2_.*",
"usrc_.*",
"umutablecp.*",
"ucp.*",
];
// C types that will be made available to rust code. Add more to this list if you want to
// generate more bindings.
static ref BINDGEN_ALLOWLIST_TYPES: Vec<&'static str> = vec![
"UAcceptResult",
"UBool",
"UBreakIterator",
"UBreakIteratorType",
"UCalendar.*",
"UCharsetDetector",
"UCharsetMatch",
"UChar.*",
"UCol.*",
"UCollation.*",
"UCollator",
"UConverter.*",
"UData.*",
"UDate.*",
"UDateFormat.*",
"UDisplayContext.*",
"UEnumeration.*",
"UErrorCode",
"UField.*",
"UFormat.*",
"UFormattedList.*",
"ULineBreakTag",
"UListFormatter.*",
"ULoc.*",
"ULOC.*",
"UMessageFormat",
"UNUM.*",
"UNumber.*",
"UParseError",
"UPlural.*",
"USentenceBreakTag",
"USet",
"UText",
"UTransDirection",
"UTransPosition",
"UTransliterator",
"UWordBreak",
"UNorm.*",
"UCPTrie.*",
"UCPTrieType",
"UCPTRIE.*",
"UPRV.*",
];
}
/// Returns true if the ICU library was compiled with renaming enabled.
fn has_renaming() -> Result<bool> {
let cpp_flags = ICUConfig::new().cppflags()?;
let found = cpp_flags.find("-DU_DISABLE_RENAMING=1");
Ok(found.is_none())
}
/// Generates a wrapper header that includes all headers of interest for binding.
///
/// This is the recommended way to bind complex libraries at the moment. Returns
/// the relative path of the generated wrapper header file with respect to some
/// path from the include dir path (`-I`).
fn generate_wrapper_header(out_dir_path: &Path, bindgen_source_modules: &[&str]) -> String {
let wrapper_path = out_dir_path.join("wrapper.h");
let mut wrapper_file = File::create(&wrapper_path).unwrap();
wrapper_file
.write_all(
concat!(
"/* Generated file, do not edit. */ \n",
"/* Assumes correct -I flag to the compiler is passed. */\n"
)
.as_bytes(),
)
.unwrap();
let includes = bindgen_source_modules
.iter()
.copied()
.map(|f| {
std::path::PathBuf::new()
.join("unicode")
.join(format!("{}.h", f))
.to_str()
.unwrap()
.to_string()
})
.map(|f| {
let file_path_str = format!("#include \"{}\"\n", f);
println!("include-file: '{}'", f);
file_path_str
})
.collect::<String>();
wrapper_file.write_all(&includes.into_bytes()).unwrap();
String::from(wrapper_path.to_str().unwrap())
}
fn run_bindgen(header_file: &str, out_dir_path: &Path) -> Result<()> {
let mut builder = bindgen::Builder::default()
.header(header_file)
.default_enum_style(bindgen::EnumVariation::Rust {
non_exhaustive: false,
})
// Bindings are pretty much unreadable without rustfmt.
.rustfmt_bindings(true)
// These attributes are useful to have around for generated types.
.derive_default(true)
.derive_hash(true)
.derive_partialord(true)
.derive_partialeq(true);
// Add all types that should be exposed to rust code.
for bindgen_type in BINDGEN_ALLOWLIST_TYPES.iter() {
builder = builder.allowlist_type(bindgen_type);
}
// Add all functions that should be exposed to rust code.
for bindgen_function in BINDGEN_ALLOWLIST_FUNCTIONS.iter() {
builder = builder.allowlist_function(bindgen_function);
}
// Add the correct clang settings.
let renaming_arg =
match has_renaming().with_context(|| "could not prepare bindgen builder")? {
true => "",
// When renaming is disabled, the functions will have a suffix that
// represents the library version in use, for example funct_64 for ICU
// version 64.
false => "-DU_DISABLE_RENAMING=1",
};
let builder = builder.clang_arg(renaming_arg);
let ld_flags = ICUConfig::new()
.ldflags()
.with_context(|| "could not prepare bindgen builder")?;
let builder = builder.clang_arg(ld_flags);
let cpp_flags = ICUConfig::new()
.cppflags()
.with_context(|| "could not prepare bindgen builder")?;
let builder = builder.clang_arg(cpp_flags);
let builder = builder.detect_include_paths(true);
let bindings = builder
.generate()
.map_err(|_| anyhow::anyhow!("could not generate bindings"))?;
let output_file_path = out_dir_path.join("lib.rs");
let output_file = output_file_path.to_str().unwrap();
bindings
.write_to_file(output_file)
.with_context(|| "while writing output")?;
Ok(())
}
// Generates the library renaming macro: this allows us to use renamed function
// names in the resulting low-level bindings library.
fn run_renamegen(out_dir_path: &Path) -> Result<()> {
let output_file_path = out_dir_path.join("macros.rs");
let mut macro_file = File::create(&output_file_path)
.with_context(|| format!("while opening {:?}", output_file_path))?;
if has_renaming()? {
println!("renaming: true");
// The library names have been renamed, need to generate a macro that
// converts the call of `foo()` into `foo_64()`.
let icu_major_version = ICUConfig::version_major()?;
let to_write = format!(
r#"
// Macros for changing function names.
// Automatically generated by build.rs.
// This library was build with version renaming, so rewrite every function name
// with its name with version number appended.
// The macro below will rename a symbol `foo::bar` to `foo::bar_{0}` (where "{0}")
// may be some other number depending on the ICU library in use.
#[cfg(feature="renaming")]
#[macro_export]
macro_rules! versioned_function {{
($i:ident) => {{
$crate::__private_do_not_use::paste::expr! {{
$crate::[< $i _{0} >]
}}
}}
}}
// This allows the user to override the renaming configuration detected from
// icu-config.
#[cfg(not(feature="renaming"))]
#[macro_export]
macro_rules! versioned_function {{
($func_name:ident) => {{
$crate::$func_name
}}
}}
"#,
icu_major_version
);
macro_file
.write_all(&to_write.into_bytes())
.with_context(|| "while writing macros.rs with renaming")
} else {
// The library names have not been renamed, generating an empty macro
println!("renaming: false");
macro_file
.write_all(
&r#"
// Macros for changing function names.
// Automatically generated by build.rs.
// There was no renaming in this one, so just short-circuit this macro.
#[macro_export]
macro_rules! versioned_function {
($func_name:path) => {
$func_name
}
}
"#
.to_string()
.into_bytes(),
)
.with_context(|| "while writing macros.rs without renaming")
}
}
/// Copies the featuers set in `Cargo.toml` into the build script. Not sure
/// why, but the features seem *ignored* when `build.rs` is used.
pub fn copy_features() -> Result<()> {
if env::var_os("CARGO_FEATURE_RENAMING").is_some() {
println!("cargo:rustc-cfg=feature=\"renaming\"");
}
if env::var_os("CARGO_FEATURE_USE_BINDGEN").is_some() {
println!("cargo:rustc-cfg=feature=\"use-bindgen\"");
}
if env::var_os("CARGO_FEATURE_ICU_CONFIG").is_some() {
println!("cargo:rustc-cfg=feature=\"icu_config\"");
}
if env::var_os("CARGO_FEATURE_ICU_VERSION_IN_ENV").is_some() {
println!("cargo:rustc-cfg=feature=\"icu_version_in_env\"");
}
let icu_major_version = ICUConfig::version_major_int()?;
println!("icu-version-major: {}", icu_major_version);
if icu_major_version >= 64 {
println!("cargo:rustc-cfg=feature=\"icu_version_64_plus\"");
}
if icu_major_version >= 67 {
println!("cargo:rustc-cfg=feature=\"icu_version_67_plus\"");
}
if icu_major_version >= 68 {
println!("cargo:rustc-cfg=feature=\"icu_version_68_plus\"");
}
// Starting from version 69, the feature flags depending on the version
// number work for up to a certain version, so that they can be retired
// over time.
if icu_major_version <= 69 {
println!("cargo:rustc-cfg=feature=\"icu_version_69_max\"");
}
Ok(())
}
pub fn icu_config_autodetect() -> Result<()> {
println!("icu-version: {}", ICUConfig::new().version()?);
println!("icu-cppflags: {}", ICUConfig::new().cppflags()?);
println!("icu-ldflags: {}", ICUConfig::new().ldflags()?);
println!("icu-has-renaming: {}", has_renaming()?);
// The path to the directory where cargo will add the output artifacts.
let out_dir = env::var("OUT_DIR").unwrap();
let out_dir_path = Path::new(&out_dir);
let header_file = generate_wrapper_header(&out_dir_path, &BINDGEN_SOURCE_MODULES);
run_bindgen(&header_file, out_dir_path).with_context(|| "while running bindgen")?;
run_renamegen(out_dir_path).with_context(|| "while running renamegen")?;
println!("cargo:install-dir={}", ICUConfig::new().install_dir()?);
let lib_dir = ICUConfig::new().libdir()?;
println!("cargo:rustc-link-search=native={}", lib_dir);
println!("cargo:rustc-flags={}", ICUConfig::new().ldflags()?);
Ok(())
}
}
fn rustc_link_libs() {
if cfg!(feature = "static") {
println!("cargo:rustc-link-lib=static=icuuc");
println!("cargo:rustc-link-lib=static=icui18n");
println!("cargo:rustc-link-lib=static:+whole-archive,-bundle=icudata");
// On systems such as macOS, libc++ is the default library
if cfg!(target_vendor = "apple") {
println!("cargo:rustc-link-lib=dylib=c++");
} else {
println!("cargo:rustc-link-lib=dylib=stdc++");
}
} else {
println!("cargo:rustc-link-lib=dylib=icuuc");
println!("cargo:rustc-link-lib=dylib=icui18n");
println!("cargo:rustc-link-lib=dylib=icudata");
}
}
#[cfg(feature = "use-bindgen")]
fn main() -> Result<(), anyhow::Error> {
use anyhow::Context;
std::env::set_var("RUST_BACKTRACE", "full");
inner::copy_features().context("while copying features")?;
if std::env::var_os("CARGO_FEATURE_ICU_CONFIG").is_none() {
return Ok(());
}
inner::icu_config_autodetect().context("while autodetecting ICU")?;
rustc_link_libs();
println!("done:true");
Ok(())
}
/// No-op if use-bindgen is disabled.
#[cfg(not(feature = "use-bindgen"))]
fn main() {
// can be used to provide an extra path to find libicuuc, libicui18n and libicudata
if let Ok(lib_dir) = std::env::var("RUST_ICU_LINK_SEARCH_DIR") {
println!("cargo:rustc-link-search=native={}", lib_dir);
}
rustc_link_libs();
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_71.rs | rust_icu_sys/bindgen/lib_71.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_71(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_71(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_71(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_71(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_71(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_71(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_71(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_71(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_71(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_71(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_71(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_71(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_71() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_71(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_71(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_71(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_71(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_71(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_71(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_71(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_71(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_71(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_71(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_71(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_71(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_71(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_71(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_71(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_71(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_71(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_71(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_71() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_71(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_71() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_71() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_71(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_71(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_71(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_71(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_71(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_71(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_71(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_71(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_71(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_71(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_71(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_71(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_71(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_71(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_71(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_71(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_71(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_71(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_71(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_71(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_71(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_BINARY_LIMIT = 72,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_71(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_71(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_71(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_71(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_71(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_71(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_71(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_71(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_71(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_71(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_71(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_71(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_71(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_71(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_71(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_71(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_71(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_71(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_71(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_71(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_71(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_71(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_71(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDIgnorable_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDStart_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDPart_71(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_tolower_71(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_toupper_71(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_totitle_71(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_foldCase_71(c: UChar32, options: u32) -> UChar32;
}
unsafe extern "C" {
pub fn u_digit_71(ch: UChar32, radix: i8) -> i32;
}
unsafe extern "C" {
pub fn u_forDigit_71(digit: i32, radix: i8) -> UChar32;
}
unsafe extern "C" {
pub fn u_charAge_71(c: UChar32, versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getUnicodeVersion_71(versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getFC_NFKC_Closure_71(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn utext_close_71(ut: *mut UText) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUTF8_71(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUChars_71(
ut: *mut UText,
s: *const UChar,
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_76.rs | rust_icu_sys/bindgen/lib_76.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type __uint16_t = ::std::os::raw::c_ushort;
pub type __uint_least16_t = __uint16_t;
pub type char16_t = __uint_least16_t;
pub type UBool = i8;
pub type UChar = char16_t;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_76(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_76(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_76(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_76(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_MF_UNRESOLVED_VARIABLE_ERROR = 65812,
U_MF_SYNTAX_ERROR = 65813,
U_MF_UNKNOWN_FUNCTION_ERROR = 65814,
U_MF_VARIANT_KEY_MISMATCH_ERROR = 65815,
U_MF_FORMATTING_ERROR = 65816,
U_MF_NONEXHAUSTIVE_PATTERN_ERROR = 65817,
U_MF_DUPLICATE_OPTION_NAME_ERROR = 65818,
U_MF_SELECTOR_ERROR = 65819,
U_MF_MISSING_SELECTOR_ANNOTATION_ERROR = 65820,
U_MF_DUPLICATE_DECLARATION_ERROR = 65821,
U_MF_OPERAND_MISMATCH_ERROR = 65822,
U_MF_DUPLICATE_VARIANT_ERROR = 65823,
U_FMT_PARSE_ERROR_LIMIT = 65824,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_76(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_76(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_76(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_76(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_76(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_76(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_76(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_76(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_76() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_76(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_76(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_76(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_76(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_76(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_76(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_76(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_76(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_76(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_76(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_76(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_76(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_76(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_76(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_76(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_76(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_76(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_76(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_76() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_76(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_76() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_76() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_76(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_76(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_76(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_76(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_76(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_76(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_76(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_76(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_76(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_76(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_76(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_76(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_76(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_76(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_76(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_76(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_76(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_76(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_76(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_76(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_76(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_IDS_UNARY_OPERATOR = 72,
UCHAR_ID_COMPAT_MATH_START = 73,
UCHAR_ID_COMPAT_MATH_CONTINUE = 74,
UCHAR_MODIFIER_COMBINING_MARK = 75,
UCHAR_BINARY_LIMIT = 76,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_IDENTIFIER_STATUS = 4121,
UCHAR_INDIC_CONJUNCT_BREAK = 4122,
UCHAR_INT_LIMIT = 4123,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_IDENTIFIER_TYPE = 28673,
UCHAR_OTHER_PROPERTY_LIMIT = 28674,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UIdentifierType {
U_ID_TYPE_NOT_CHARACTER = 0,
U_ID_TYPE_DEPRECATED = 1,
U_ID_TYPE_DEFAULT_IGNORABLE = 2,
U_ID_TYPE_NOT_NFKC = 3,
U_ID_TYPE_NOT_XID = 4,
U_ID_TYPE_EXCLUSION = 5,
U_ID_TYPE_OBSOLETE = 6,
U_ID_TYPE_TECHNICAL = 7,
U_ID_TYPE_UNCOMMON_USE = 8,
U_ID_TYPE_LIMITED_USE = 9,
U_ID_TYPE_INCLUSION = 10,
U_ID_TYPE_RECOMMENDED = 11,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_76(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_76(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_76(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_76(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_76(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_76(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_76(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_76(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_76(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_76(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_76(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_76(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_76(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_76(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_76(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_76(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_76(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_76(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_76(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_76(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_76(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_76(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_76(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_76(c: UChar32) -> UBool;
}
unsafe extern "C" {
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_63.rs | rust_icu_sys/bindgen/lib_63.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_63(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_63(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_63(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_63(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_STANDARD_ERROR_LIMIT = 31,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_63(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_63(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_63(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_63(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_63(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_63(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_63(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_63(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_63() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_63(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_63(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_63(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_63(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_63(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_63(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_63(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_63(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_63(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_63(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_63(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_63(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_63(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_63(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_63(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_63(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_63(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_63(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_63() -> i32;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_63() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_63() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_63(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_63(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_63(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_63(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_63(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_63(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_63(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_63(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_63(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_63(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_63(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_63(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_63(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_63(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_63(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_63(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_63(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_63(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_63(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_63(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_63(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BINARY_LIMIT = 65,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_63(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_63(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_63(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_63(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_63(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_63(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_63(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_63(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_63(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_63(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_63(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_63(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_63(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_63(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_63(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_63(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_63(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_63(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_63(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_63(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_63(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_63(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDIgnorable_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDStart_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDPart_63(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_tolower_63(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_toupper_63(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_totitle_63(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_foldCase_63(c: UChar32, options: u32) -> UChar32;
}
unsafe extern "C" {
pub fn u_digit_63(ch: UChar32, radix: i8) -> i32;
}
unsafe extern "C" {
pub fn u_forDigit_63(digit: i32, radix: i8) -> UChar32;
}
unsafe extern "C" {
pub fn u_charAge_63(c: UChar32, versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getUnicodeVersion_63(versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getFC_NFKC_Closure_63(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn utext_close_63(ut: *mut UText) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUTF8_63(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUChars_63(
ut: *mut UText,
s: *const UChar,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_clone_63(
dest: *mut UText,
src: *const UText,
deep: UBool,
readOnly: UBool,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_equals_63(a: *const UText, b: *const UText) -> UBool;
}
unsafe extern "C" {
pub fn utext_nativeLength_63(ut: *mut UText) -> i64;
}
unsafe extern "C" {
pub fn utext_isLengthExpensive_63(ut: *const UText) -> UBool;
}
unsafe extern "C" {
pub fn utext_char32At_63(ut: *mut UText, nativeIndex: i64) -> UChar32;
}
unsafe extern "C" {
pub fn utext_current32_63(ut: *mut UText) -> UChar32;
}
unsafe extern "C" {
pub fn utext_next32_63(ut: *mut UText) -> UChar32;
}
unsafe extern "C" {
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_73.rs | rust_icu_sys/bindgen/lib_73.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_73(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_73(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_73(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_73(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_73(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_73(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_73(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_73(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_73(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_73(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_73(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_73(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_73() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_73(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_73(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_73(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_73(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_73(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_73(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_73(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_73(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_73(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_73(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_73(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_73(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_73(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_73(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_73(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_73(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_73(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_73(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_73() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_73(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_73() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_73() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_73(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_73(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_73(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_73(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_73(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_73(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_73(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_73(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_73(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_73(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_73(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_73(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_73(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_73(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_73(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_73(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_73(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_73(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_73(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_73(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_73(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_BINARY_LIMIT = 72,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_73(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_73(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_73(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_73(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_73(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_73(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_73(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_73(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_73(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_73(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_73(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_73(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_73(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_73(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_73(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_73(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_73(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_73(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_73(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_73(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_73(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_73(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_73(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDIgnorable_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDStart_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDPart_73(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_tolower_73(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_toupper_73(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_totitle_73(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_foldCase_73(c: UChar32, options: u32) -> UChar32;
}
unsafe extern "C" {
pub fn u_digit_73(ch: UChar32, radix: i8) -> i32;
}
unsafe extern "C" {
pub fn u_forDigit_73(digit: i32, radix: i8) -> UChar32;
}
unsafe extern "C" {
pub fn u_charAge_73(c: UChar32, versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getUnicodeVersion_73(versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getFC_NFKC_Closure_73(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn utext_close_73(ut: *mut UText) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUTF8_73(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUChars_73(
ut: *mut UText,
s: *const UChar,
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_77.rs | rust_icu_sys/bindgen/lib_77.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type __uint16_t = ::std::os::raw::c_ushort;
pub type __uint_least16_t = __uint16_t;
pub type char16_t = __uint_least16_t;
pub type UBool = i8;
pub type UChar = char16_t;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_77(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_77(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_77(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_77(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_MF_UNRESOLVED_VARIABLE_ERROR = 65812,
U_MF_SYNTAX_ERROR = 65813,
U_MF_UNKNOWN_FUNCTION_ERROR = 65814,
U_MF_VARIANT_KEY_MISMATCH_ERROR = 65815,
U_MF_FORMATTING_ERROR = 65816,
U_MF_NONEXHAUSTIVE_PATTERN_ERROR = 65817,
U_MF_DUPLICATE_OPTION_NAME_ERROR = 65818,
U_MF_SELECTOR_ERROR = 65819,
U_MF_MISSING_SELECTOR_ANNOTATION_ERROR = 65820,
U_MF_DUPLICATE_DECLARATION_ERROR = 65821,
U_MF_OPERAND_MISMATCH_ERROR = 65822,
U_MF_DUPLICATE_VARIANT_ERROR = 65823,
U_MF_BAD_OPTION = 65824,
U_FMT_PARSE_ERROR_LIMIT = 65825,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_77(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_77(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_77(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_77(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_77(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_77(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_77(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_77(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_77() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_77(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_77(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_77(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_77(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_77(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_77(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_77(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_77(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_77(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_77(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_77(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_77(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_77(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_77(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_77(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_77(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_77(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_77(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_77() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_77(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_77() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_77() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_77(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_77(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_77(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_77(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_77(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_77(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_77(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_77(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_77(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_77(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_77(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_77(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_77(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_77(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_77(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_77(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_77(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_77(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_77(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_77(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_77(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_IDS_UNARY_OPERATOR = 72,
UCHAR_ID_COMPAT_MATH_START = 73,
UCHAR_ID_COMPAT_MATH_CONTINUE = 74,
UCHAR_MODIFIER_COMBINING_MARK = 75,
UCHAR_BINARY_LIMIT = 76,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_IDENTIFIER_STATUS = 4121,
UCHAR_INDIC_CONJUNCT_BREAK = 4122,
UCHAR_INT_LIMIT = 4123,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_IDENTIFIER_TYPE = 28673,
UCHAR_OTHER_PROPERTY_LIMIT = 28674,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UIdentifierType {
U_ID_TYPE_NOT_CHARACTER = 0,
U_ID_TYPE_DEPRECATED = 1,
U_ID_TYPE_DEFAULT_IGNORABLE = 2,
U_ID_TYPE_NOT_NFKC = 3,
U_ID_TYPE_NOT_XID = 4,
U_ID_TYPE_EXCLUSION = 5,
U_ID_TYPE_OBSOLETE = 6,
U_ID_TYPE_TECHNICAL = 7,
U_ID_TYPE_UNCOMMON_USE = 8,
U_ID_TYPE_LIMITED_USE = 9,
U_ID_TYPE_INCLUSION = 10,
U_ID_TYPE_RECOMMENDED = 11,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_77(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_77(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_77(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_77(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_77(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_77(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_77(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_77(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_77(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_77(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_77(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_77(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_77(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_77(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_77(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_77(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_77(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_77(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_77(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_77(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_77(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_77(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_77(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_77(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_77(c: UChar32) -> UBool;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_74.rs | rust_icu_sys/bindgen/lib_74.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_74(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_74(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_74(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_74(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_74(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_74(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_74(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_74(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_74(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_74(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_74(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_74(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_74() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_74(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_74(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_74(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_74(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_74(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_74(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_74(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_74(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_74(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_74(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_74(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_74(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_74(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_74(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_74(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_74(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_74(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_74(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_74() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_74(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_74() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_74() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_74(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_74(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_74(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_74(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_74(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_74(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_74(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_74(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_74(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_74(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_74(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_74(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_74(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_74(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_74(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_74(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_74(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_74(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_74(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_74(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_74(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_IDS_UNARY_OPERATOR = 72,
UCHAR_ID_COMPAT_MATH_START = 73,
UCHAR_ID_COMPAT_MATH_CONTINUE = 74,
UCHAR_BINARY_LIMIT = 75,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_74(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_74(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_74(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_74(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_74(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_74(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_74(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_74(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_74(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_74(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_74(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_74(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_74(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_74(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_74(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_74(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_74(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_74(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_74(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_74(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_74(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_74(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_74(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDIgnorable_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDStart_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDPart_74(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_tolower_74(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_toupper_74(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_totitle_74(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_foldCase_74(c: UChar32, options: u32) -> UChar32;
}
unsafe extern "C" {
pub fn u_digit_74(ch: UChar32, radix: i8) -> i32;
}
unsafe extern "C" {
pub fn u_forDigit_74(digit: i32, radix: i8) -> UChar32;
}
unsafe extern "C" {
pub fn u_charAge_74(c: UChar32, versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getUnicodeVersion_74(versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getFC_NFKC_Closure_74(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn utext_close_74(ut: *mut UText) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUTF8_74(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/macros.rs | rust_icu_sys/bindgen/macros.rs | // Macros for changing function names.
// This is created and edited manually, but should be kept roughly in sync with `build.rs`.
/// This library was build with version renaming, so rewrite every function name
/// with its name with version number appended.
/// The macro will rename a symbol `foo::bar` to `foo::bar_64` (where "64")
/// may be some other number depending on the ICU library in use.
#[cfg(all(feature = "renaming", not(feature = "icu_version_in_env")))]
#[macro_export]
macro_rules! versioned_function {
($i:ident) => {
$crate::__private_do_not_use::paste::expr! {
$crate::[< $i _ 64 >]
}
}
}
/// This library was build with version renaming, so rewrite every function name
/// with its name with version number appended.
///
/// The macro will rename a symbol `foo::bar` to `foo::bar_XX` (where "XX")
/// is a string coming from the environment variable RUST_ICU_MAJOR_VERSION_NUMBER,
/// which is expected to be defined at compile time.
#[cfg(all(feature = "renaming", feature = "icu_version_in_env"))]
#[macro_export]
macro_rules! versioned_function {
($i:ident) => {
$crate::__private_do_not_use::paste::expr! {
$crate::[< $i _ env!("RUST_ICU_MAJOR_VERSION_NUMBER") >]
}
}
}
/// This macro will be used when no function renaming is needed.
#[cfg(not(feature = "renaming"))]
#[macro_export]
macro_rules! versioned_function {
($func_name:ident) => {
$crate::$func_name
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_70.rs | rust_icu_sys/bindgen/lib_70.rs | /* automatically generated by rust-bindgen 0.66.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
extern "C" {
pub fn u_versionFromString_70(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn u_versionFromUString_70(versionArray: *mut u8, versionString: *const UChar);
}
extern "C" {
pub fn u_versionToString_70(versionArray: *mut u8, versionString: *mut ::std::os::raw::c_char);
}
extern "C" {
pub fn u_getVersion_70(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
extern "C" {
pub fn u_errorName_70(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
extern "C" {
pub fn uenum_close_70(en: *mut UEnumeration);
}
extern "C" {
pub fn uenum_count_70(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
extern "C" {
pub fn uenum_unext_70(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
extern "C" {
pub fn uenum_next_70(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uenum_reset_70(en: *mut UEnumeration, status: *mut UErrorCode);
}
extern "C" {
pub fn uenum_openUCharStringsEnumeration_70(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
extern "C" {
pub fn uenum_openCharStringsEnumeration_70(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
extern "C" {
pub fn uloc_getDefault_70() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_setDefault_70(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
extern "C" {
pub fn uloc_getLanguage_70(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getScript_70(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getCountry_70(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getVariant_70(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getName_70(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_canonicalize_70(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getISO3Language_70(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_getISO3Country_70(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_getLCID_70(localeID: *const ::std::os::raw::c_char) -> u32;
}
extern "C" {
pub fn uloc_getDisplayLanguage_70(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayScript_70(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayCountry_70(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayVariant_70(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayKeyword_70(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayKeywordValue_70(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getDisplayName_70(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getAvailable_70(n: i32) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_countAvailable_70() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
extern "C" {
pub fn uloc_openAvailableByType_70(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
extern "C" {
pub fn uloc_getISOLanguages_70() -> *const *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_getISOCountries_70() -> *const *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_getParent_70(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getBaseName_70(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_openKeywords_70(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
extern "C" {
pub fn uloc_getKeywordValue_70(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_setKeywordValue_70(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_isRightToLeft_70(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
extern "C" {
pub fn uloc_getCharacterOrientation_70(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
extern "C" {
pub fn uloc_getLineOrientation_70(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
extern "C" {
pub fn uloc_acceptLanguageFromHTTP_70(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_acceptLanguage_70(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_getLocaleForLCID_70(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_addLikelySubtags_70(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_minimizeSubtags_70(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_forLanguageTag_70(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_toLanguageTag_70(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn uloc_toUnicodeLocaleKey_70(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_toUnicodeLocaleType_70(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_toLegacyKey_70(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn uloc_toLegacyType_70(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
extern "C" {
pub fn ucpmap_get_70(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
extern "C" {
pub fn ucpmap_getRange_70(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_BINARY_LIMIT = 72,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
extern "C" {
pub fn u_hasBinaryProperty_70(c: UChar32, which: UProperty) -> UBool;
}
extern "C" {
pub fn u_stringHasBinaryProperty_70(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
extern "C" {
pub fn u_getBinaryPropertySet_70(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
extern "C" {
pub fn u_isUAlphabetic_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isULowercase_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isUUppercase_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isUWhiteSpace_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_getIntPropertyValue_70(c: UChar32, which: UProperty) -> i32;
}
extern "C" {
pub fn u_getIntPropertyMinValue_70(which: UProperty) -> i32;
}
extern "C" {
pub fn u_getIntPropertyMaxValue_70(which: UProperty) -> i32;
}
extern "C" {
pub fn u_getIntPropertyMap_70(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
extern "C" {
pub fn u_getNumericValue_70(c: UChar32) -> f64;
}
extern "C" {
pub fn u_islower_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isupper_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_istitle_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isdigit_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isalpha_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isalnum_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isxdigit_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_ispunct_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isgraph_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isblank_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isdefined_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isspace_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isJavaSpaceChar_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isWhitespace_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_iscntrl_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isISOControl_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isprint_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isbase_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_charDirection_70(c: UChar32) -> UCharDirection;
}
extern "C" {
pub fn u_isMirrored_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_charMirror_70(c: UChar32) -> UChar32;
}
extern "C" {
pub fn u_getBidiPairedBracket_70(c: UChar32) -> UChar32;
}
extern "C" {
pub fn u_charType_70(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
extern "C" {
pub fn u_enumCharTypes_70(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
extern "C" {
pub fn u_getCombiningClass_70(c: UChar32) -> u8;
}
extern "C" {
pub fn u_charDigitValue_70(c: UChar32) -> i32;
}
extern "C" {
pub fn u_charName_70(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn u_getISOComment_70(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn u_charFromName_70(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
extern "C" {
pub fn u_enumCharNames_70(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
extern "C" {
pub fn u_getPropertyName_70(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn u_getPropertyEnum_70(alias: *const ::std::os::raw::c_char) -> UProperty;
}
extern "C" {
pub fn u_getPropertyValueName_70(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn u_getPropertyValueEnum_70(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
extern "C" {
pub fn u_isIDStart_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isIDPart_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isIDIgnorable_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isJavaIDStart_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_isJavaIDPart_70(c: UChar32) -> UBool;
}
extern "C" {
pub fn u_tolower_70(c: UChar32) -> UChar32;
}
extern "C" {
pub fn u_toupper_70(c: UChar32) -> UChar32;
}
extern "C" {
pub fn u_totitle_70(c: UChar32) -> UChar32;
}
extern "C" {
pub fn u_foldCase_70(c: UChar32, options: u32) -> UChar32;
}
extern "C" {
pub fn u_digit_70(ch: UChar32, radix: i8) -> i32;
}
extern "C" {
pub fn u_forDigit_70(digit: i32, radix: i8) -> UChar32;
}
extern "C" {
pub fn u_charAge_70(c: UChar32, versionArray: *mut u8);
}
extern "C" {
pub fn u_getUnicodeVersion_70(versionArray: *mut u8);
}
extern "C" {
pub fn u_getFC_NFKC_Closure_70(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
extern "C" {
pub fn utext_close_70(ut: *mut UText) -> *mut UText;
}
extern "C" {
pub fn utext_openUTF8_70(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
extern "C" {
pub fn utext_openUChars_70(
ut: *mut UText,
s: *const UChar,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
extern "C" {
pub fn utext_clone_70(
dest: *mut UText,
src: *const UText,
deep: UBool,
readOnly: UBool,
status: *mut UErrorCode,
) -> *mut UText;
}
extern "C" {
pub fn utext_equals_70(a: *const UText, b: *const UText) -> UBool;
}
extern "C" {
pub fn utext_nativeLength_70(ut: *mut UText) -> i64;
}
extern "C" {
pub fn utext_isLengthExpensive_70(ut: *const UText) -> UBool;
}
extern "C" {
pub fn utext_char32At_70(ut: *mut UText, nativeIndex: i64) -> UChar32;
}
extern "C" {
pub fn utext_current32_70(ut: *mut UText) -> UChar32;
}
extern "C" {
pub fn utext_next32_70(ut: *mut UText) -> UChar32;
}
extern "C" {
pub fn utext_previous32_70(ut: *mut UText) -> UChar32;
}
extern "C" {
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen/lib_72.rs | rust_icu_sys/bindgen/lib_72.rs | /* automatically generated by rust-bindgen 0.72.1 */
pub type wchar_t = ::std::os::raw::c_int;
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
pub type UVersionInfo = [u8; 4usize];
unsafe extern "C" {
pub fn u_versionFromString_72(
versionArray: *mut u8,
versionString: *const ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_versionFromUString_72(versionArray: *mut u8, versionString: *const UChar);
}
unsafe extern "C" {
pub fn u_versionToString_72(
versionArray: *const u8,
versionString: *mut ::std::os::raw::c_char,
);
}
unsafe extern "C" {
pub fn u_getVersion_72(versionArray: *mut u8);
}
pub type UDate = f64;
impl UErrorCode {
pub const U_ERROR_WARNING_START: UErrorCode = UErrorCode::U_USING_FALLBACK_WARNING;
}
impl UErrorCode {
pub const U_PARSE_ERROR_START: UErrorCode = UErrorCode::U_BAD_VARIABLE_DEFINITION;
}
impl UErrorCode {
pub const U_FMT_PARSE_ERROR_START: UErrorCode = UErrorCode::U_UNEXPECTED_TOKEN;
}
impl UErrorCode {
pub const U_MULTIPLE_DECIMAL_SEPERATORS: UErrorCode = UErrorCode::U_MULTIPLE_DECIMAL_SEPARATORS;
}
impl UErrorCode {
pub const U_BRK_ERROR_START: UErrorCode = UErrorCode::U_BRK_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_REGEX_ERROR_START: UErrorCode = UErrorCode::U_REGEX_INTERNAL_ERROR;
}
impl UErrorCode {
pub const U_IDNA_ERROR_START: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_PROHIBITED_ERROR: UErrorCode = UErrorCode::U_IDNA_PROHIBITED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_UNASSIGNED_ERROR: UErrorCode = UErrorCode::U_IDNA_UNASSIGNED_ERROR;
}
impl UErrorCode {
pub const U_STRINGPREP_CHECK_BIDI_ERROR: UErrorCode = UErrorCode::U_IDNA_CHECK_BIDI_ERROR;
}
impl UErrorCode {
pub const U_PLUGIN_TOO_HIGH: UErrorCode = UErrorCode::U_PLUGIN_ERROR_START;
}
impl UErrorCode {
pub const U_ERROR_LIMIT: UErrorCode = UErrorCode::U_PLUGIN_ERROR_LIMIT;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UErrorCode {
U_USING_FALLBACK_WARNING = -128,
U_USING_DEFAULT_WARNING = -127,
U_SAFECLONE_ALLOCATED_WARNING = -126,
U_STATE_OLD_WARNING = -125,
U_STRING_NOT_TERMINATED_WARNING = -124,
U_SORT_KEY_TOO_SHORT_WARNING = -123,
U_AMBIGUOUS_ALIAS_WARNING = -122,
U_DIFFERENT_UCA_VERSION = -121,
U_PLUGIN_CHANGED_LEVEL_WARNING = -120,
U_ERROR_WARNING_LIMIT = -119,
U_ZERO_ERROR = 0,
U_ILLEGAL_ARGUMENT_ERROR = 1,
U_MISSING_RESOURCE_ERROR = 2,
U_INVALID_FORMAT_ERROR = 3,
U_FILE_ACCESS_ERROR = 4,
U_INTERNAL_PROGRAM_ERROR = 5,
U_MESSAGE_PARSE_ERROR = 6,
U_MEMORY_ALLOCATION_ERROR = 7,
U_INDEX_OUTOFBOUNDS_ERROR = 8,
U_PARSE_ERROR = 9,
U_INVALID_CHAR_FOUND = 10,
U_TRUNCATED_CHAR_FOUND = 11,
U_ILLEGAL_CHAR_FOUND = 12,
U_INVALID_TABLE_FORMAT = 13,
U_INVALID_TABLE_FILE = 14,
U_BUFFER_OVERFLOW_ERROR = 15,
U_UNSUPPORTED_ERROR = 16,
U_RESOURCE_TYPE_MISMATCH = 17,
U_ILLEGAL_ESCAPE_SEQUENCE = 18,
U_UNSUPPORTED_ESCAPE_SEQUENCE = 19,
U_NO_SPACE_AVAILABLE = 20,
U_CE_NOT_FOUND_ERROR = 21,
U_PRIMARY_TOO_LONG_ERROR = 22,
U_STATE_TOO_OLD_ERROR = 23,
U_TOO_MANY_ALIASES_ERROR = 24,
U_ENUM_OUT_OF_SYNC_ERROR = 25,
U_INVARIANT_CONVERSION_ERROR = 26,
U_INVALID_STATE_ERROR = 27,
U_COLLATOR_VERSION_MISMATCH = 28,
U_USELESS_COLLATOR_ERROR = 29,
U_NO_WRITE_PERMISSION = 30,
U_INPUT_TOO_LONG_ERROR = 31,
U_STANDARD_ERROR_LIMIT = 32,
U_BAD_VARIABLE_DEFINITION = 65536,
U_MALFORMED_RULE = 65537,
U_MALFORMED_SET = 65538,
U_MALFORMED_SYMBOL_REFERENCE = 65539,
U_MALFORMED_UNICODE_ESCAPE = 65540,
U_MALFORMED_VARIABLE_DEFINITION = 65541,
U_MALFORMED_VARIABLE_REFERENCE = 65542,
U_MISMATCHED_SEGMENT_DELIMITERS = 65543,
U_MISPLACED_ANCHOR_START = 65544,
U_MISPLACED_CURSOR_OFFSET = 65545,
U_MISPLACED_QUANTIFIER = 65546,
U_MISSING_OPERATOR = 65547,
U_MISSING_SEGMENT_CLOSE = 65548,
U_MULTIPLE_ANTE_CONTEXTS = 65549,
U_MULTIPLE_CURSORS = 65550,
U_MULTIPLE_POST_CONTEXTS = 65551,
U_TRAILING_BACKSLASH = 65552,
U_UNDEFINED_SEGMENT_REFERENCE = 65553,
U_UNDEFINED_VARIABLE = 65554,
U_UNQUOTED_SPECIAL = 65555,
U_UNTERMINATED_QUOTE = 65556,
U_RULE_MASK_ERROR = 65557,
U_MISPLACED_COMPOUND_FILTER = 65558,
U_MULTIPLE_COMPOUND_FILTERS = 65559,
U_INVALID_RBT_SYNTAX = 65560,
U_INVALID_PROPERTY_PATTERN = 65561,
U_MALFORMED_PRAGMA = 65562,
U_UNCLOSED_SEGMENT = 65563,
U_ILLEGAL_CHAR_IN_SEGMENT = 65564,
U_VARIABLE_RANGE_EXHAUSTED = 65565,
U_VARIABLE_RANGE_OVERLAP = 65566,
U_ILLEGAL_CHARACTER = 65567,
U_INTERNAL_TRANSLITERATOR_ERROR = 65568,
U_INVALID_ID = 65569,
U_INVALID_FUNCTION = 65570,
U_PARSE_ERROR_LIMIT = 65571,
U_UNEXPECTED_TOKEN = 65792,
U_MULTIPLE_DECIMAL_SEPARATORS = 65793,
U_MULTIPLE_EXPONENTIAL_SYMBOLS = 65794,
U_MALFORMED_EXPONENTIAL_PATTERN = 65795,
U_MULTIPLE_PERCENT_SYMBOLS = 65796,
U_MULTIPLE_PERMILL_SYMBOLS = 65797,
U_MULTIPLE_PAD_SPECIFIERS = 65798,
U_PATTERN_SYNTAX_ERROR = 65799,
U_ILLEGAL_PAD_POSITION = 65800,
U_UNMATCHED_BRACES = 65801,
U_UNSUPPORTED_PROPERTY = 65802,
U_UNSUPPORTED_ATTRIBUTE = 65803,
U_ARGUMENT_TYPE_MISMATCH = 65804,
U_DUPLICATE_KEYWORD = 65805,
U_UNDEFINED_KEYWORD = 65806,
U_DEFAULT_KEYWORD_MISSING = 65807,
U_DECIMAL_NUMBER_SYNTAX_ERROR = 65808,
U_FORMAT_INEXACT_ERROR = 65809,
U_NUMBER_ARG_OUTOFBOUNDS_ERROR = 65810,
U_NUMBER_SKELETON_SYNTAX_ERROR = 65811,
U_FMT_PARSE_ERROR_LIMIT = 65812,
U_BRK_INTERNAL_ERROR = 66048,
U_BRK_HEX_DIGITS_EXPECTED = 66049,
U_BRK_SEMICOLON_EXPECTED = 66050,
U_BRK_RULE_SYNTAX = 66051,
U_BRK_UNCLOSED_SET = 66052,
U_BRK_ASSIGN_ERROR = 66053,
U_BRK_VARIABLE_REDFINITION = 66054,
U_BRK_MISMATCHED_PAREN = 66055,
U_BRK_NEW_LINE_IN_QUOTED_STRING = 66056,
U_BRK_UNDEFINED_VARIABLE = 66057,
U_BRK_INIT_ERROR = 66058,
U_BRK_RULE_EMPTY_SET = 66059,
U_BRK_UNRECOGNIZED_OPTION = 66060,
U_BRK_MALFORMED_RULE_TAG = 66061,
U_BRK_ERROR_LIMIT = 66062,
U_REGEX_INTERNAL_ERROR = 66304,
U_REGEX_RULE_SYNTAX = 66305,
U_REGEX_INVALID_STATE = 66306,
U_REGEX_BAD_ESCAPE_SEQUENCE = 66307,
U_REGEX_PROPERTY_SYNTAX = 66308,
U_REGEX_UNIMPLEMENTED = 66309,
U_REGEX_MISMATCHED_PAREN = 66310,
U_REGEX_NUMBER_TOO_BIG = 66311,
U_REGEX_BAD_INTERVAL = 66312,
U_REGEX_MAX_LT_MIN = 66313,
U_REGEX_INVALID_BACK_REF = 66314,
U_REGEX_INVALID_FLAG = 66315,
U_REGEX_LOOK_BEHIND_LIMIT = 66316,
U_REGEX_SET_CONTAINS_STRING = 66317,
U_REGEX_OCTAL_TOO_BIG = 66318,
U_REGEX_MISSING_CLOSE_BRACKET = 66319,
U_REGEX_INVALID_RANGE = 66320,
U_REGEX_STACK_OVERFLOW = 66321,
U_REGEX_TIME_OUT = 66322,
U_REGEX_STOPPED_BY_CALLER = 66323,
U_REGEX_PATTERN_TOO_BIG = 66324,
U_REGEX_INVALID_CAPTURE_GROUP_NAME = 66325,
U_REGEX_ERROR_LIMIT = 66326,
U_IDNA_PROHIBITED_ERROR = 66560,
U_IDNA_UNASSIGNED_ERROR = 66561,
U_IDNA_CHECK_BIDI_ERROR = 66562,
U_IDNA_STD3_ASCII_RULES_ERROR = 66563,
U_IDNA_ACE_PREFIX_ERROR = 66564,
U_IDNA_VERIFICATION_ERROR = 66565,
U_IDNA_LABEL_TOO_LONG_ERROR = 66566,
U_IDNA_ZERO_LENGTH_LABEL_ERROR = 66567,
U_IDNA_DOMAIN_NAME_TOO_LONG_ERROR = 66568,
U_IDNA_ERROR_LIMIT = 66569,
U_PLUGIN_ERROR_START = 66816,
U_PLUGIN_DIDNT_SET_LEVEL = 66817,
U_PLUGIN_ERROR_LIMIT = 66818,
}
unsafe extern "C" {
pub fn u_errorName_72(code: UErrorCode) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UEnumeration {
_unused: [u8; 0],
}
unsafe extern "C" {
pub fn uenum_close_72(en: *mut UEnumeration);
}
unsafe extern "C" {
pub fn uenum_count_72(en: *mut UEnumeration, status: *mut UErrorCode) -> i32;
}
unsafe extern "C" {
pub fn uenum_unext_72(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const UChar;
}
unsafe extern "C" {
pub fn uenum_next_72(
en: *mut UEnumeration,
resultLength: *mut i32,
status: *mut UErrorCode,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uenum_reset_72(en: *mut UEnumeration, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uenum_openUCharStringsEnumeration_72(
strings: *const *const UChar,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uenum_openCharStringsEnumeration_72(
strings: *const *const ::std::os::raw::c_char,
count: i32,
ec: *mut UErrorCode,
) -> *mut UEnumeration;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocDataLocaleType {
ULOC_ACTUAL_LOCALE = 0,
ULOC_VALID_LOCALE = 1,
ULOC_REQUESTED_LOCALE = 2,
ULOC_DATA_LOCALE_TYPE_LIMIT = 3,
}
unsafe extern "C" {
pub fn uloc_getDefault_72() -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_setDefault_72(localeID: *const ::std::os::raw::c_char, status: *mut UErrorCode);
}
unsafe extern "C" {
pub fn uloc_getLanguage_72(
localeID: *const ::std::os::raw::c_char,
language: *mut ::std::os::raw::c_char,
languageCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getScript_72(
localeID: *const ::std::os::raw::c_char,
script: *mut ::std::os::raw::c_char,
scriptCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getCountry_72(
localeID: *const ::std::os::raw::c_char,
country: *mut ::std::os::raw::c_char,
countryCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getVariant_72(
localeID: *const ::std::os::raw::c_char,
variant: *mut ::std::os::raw::c_char,
variantCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getName_72(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_canonicalize_72(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getISO3Language_72(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISO3Country_72(
localeID: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getLCID_72(localeID: *const ::std::os::raw::c_char) -> u32;
}
unsafe extern "C" {
pub fn uloc_getDisplayLanguage_72(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
language: *mut UChar,
languageCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayScript_72(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
script: *mut UChar,
scriptCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayCountry_72(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
country: *mut UChar,
countryCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayVariant_72(
locale: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
variant: *mut UChar,
variantCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeyword_72(
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayKeywordValue_72(
locale: *const ::std::os::raw::c_char,
keyword: *const ::std::os::raw::c_char,
displayLocale: *const ::std::os::raw::c_char,
dest: *mut UChar,
destCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getDisplayName_72(
localeID: *const ::std::os::raw::c_char,
inLocaleID: *const ::std::os::raw::c_char,
result: *mut UChar,
maxResultSize: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getAvailable_72(n: i32) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_countAvailable_72() -> i32;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULocAvailableType {
ULOC_AVAILABLE_DEFAULT = 0,
ULOC_AVAILABLE_ONLY_LEGACY_ALIASES = 1,
ULOC_AVAILABLE_WITH_LEGACY_ALIASES = 2,
ULOC_AVAILABLE_COUNT = 3,
}
unsafe extern "C" {
pub fn uloc_openAvailableByType_72(
type_: ULocAvailableType,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getISOLanguages_72() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getISOCountries_72() -> *const *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_getParent_72(
localeID: *const ::std::os::raw::c_char,
parent: *mut ::std::os::raw::c_char,
parentCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getBaseName_72(
localeID: *const ::std::os::raw::c_char,
name: *mut ::std::os::raw::c_char,
nameCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_openKeywords_72(
localeID: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> *mut UEnumeration;
}
unsafe extern "C" {
pub fn uloc_getKeywordValue_72(
localeID: *const ::std::os::raw::c_char,
keywordName: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_setKeywordValue_72(
keywordName: *const ::std::os::raw::c_char,
keywordValue: *const ::std::os::raw::c_char,
buffer: *mut ::std::os::raw::c_char,
bufferCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_isRightToLeft_72(locale: *const ::std::os::raw::c_char) -> UBool;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum ULayoutType {
ULOC_LAYOUT_LTR = 0,
ULOC_LAYOUT_RTL = 1,
ULOC_LAYOUT_TTB = 2,
ULOC_LAYOUT_BTT = 3,
ULOC_LAYOUT_UNKNOWN = 4,
}
unsafe extern "C" {
pub fn uloc_getCharacterOrientation_72(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
unsafe extern "C" {
pub fn uloc_getLineOrientation_72(
localeId: *const ::std::os::raw::c_char,
status: *mut UErrorCode,
) -> ULayoutType;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UAcceptResult {
ULOC_ACCEPT_FAILED = 0,
ULOC_ACCEPT_VALID = 1,
ULOC_ACCEPT_FALLBACK = 2,
}
unsafe extern "C" {
pub fn uloc_acceptLanguageFromHTTP_72(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
httpAcceptLanguage: *const ::std::os::raw::c_char,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_acceptLanguage_72(
result: *mut ::std::os::raw::c_char,
resultAvailable: i32,
outResult: *mut UAcceptResult,
acceptList: *mut *const ::std::os::raw::c_char,
acceptListCount: i32,
availableLocales: *mut UEnumeration,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_getLocaleForLCID_72(
hostID: u32,
locale: *mut ::std::os::raw::c_char,
localeCapacity: i32,
status: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_addLikelySubtags_72(
localeID: *const ::std::os::raw::c_char,
maximizedLocaleID: *mut ::std::os::raw::c_char,
maximizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_minimizeSubtags_72(
localeID: *const ::std::os::raw::c_char,
minimizedLocaleID: *mut ::std::os::raw::c_char,
minimizedLocaleIDCapacity: i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_forLanguageTag_72(
langtag: *const ::std::os::raw::c_char,
localeID: *mut ::std::os::raw::c_char,
localeIDCapacity: i32,
parsedLength: *mut i32,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toLanguageTag_72(
localeID: *const ::std::os::raw::c_char,
langtag: *mut ::std::os::raw::c_char,
langtagCapacity: i32,
strict: UBool,
err: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleKey_72(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toUnicodeLocaleType_72(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyKey_72(
keyword: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn uloc_toLegacyType_72(
keyword: *const ::std::os::raw::c_char,
value: *const ::std::os::raw::c_char,
) -> *const ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UCPMap {
_unused: [u8; 0],
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPMapRangeOption {
UCPMAP_RANGE_NORMAL = 0,
UCPMAP_RANGE_FIXED_LEAD_SURROGATES = 1,
UCPMAP_RANGE_FIXED_ALL_SURROGATES = 2,
}
unsafe extern "C" {
pub fn ucpmap_get_72(map: *const UCPMap, c: UChar32) -> u32;
}
pub type UCPMapValueFilter = ::std::option::Option<
unsafe extern "C" fn(context: *const ::std::os::raw::c_void, value: u32) -> u32,
>;
unsafe extern "C" {
pub fn ucpmap_getRange_72(
map: *const UCPMap,
start: UChar32,
option: UCPMapRangeOption,
surrogateValue: u32,
filter: UCPMapValueFilter,
context: *const ::std::os::raw::c_void,
pValue: *mut u32,
) -> UChar32;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
impl UProperty {
pub const UCHAR_BINARY_START: UProperty = UProperty::UCHAR_ALPHABETIC;
}
impl UProperty {
pub const UCHAR_INT_START: UProperty = UProperty::UCHAR_BIDI_CLASS;
}
impl UProperty {
pub const UCHAR_MASK_START: UProperty = UProperty::UCHAR_GENERAL_CATEGORY_MASK;
}
impl UProperty {
pub const UCHAR_DOUBLE_START: UProperty = UProperty::UCHAR_NUMERIC_VALUE;
}
impl UProperty {
pub const UCHAR_STRING_START: UProperty = UProperty::UCHAR_AGE;
}
impl UProperty {
pub const UCHAR_OTHER_PROPERTY_START: UProperty = UProperty::UCHAR_SCRIPT_EXTENSIONS;
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UProperty {
UCHAR_ALPHABETIC = 0,
UCHAR_ASCII_HEX_DIGIT = 1,
UCHAR_BIDI_CONTROL = 2,
UCHAR_BIDI_MIRRORED = 3,
UCHAR_DASH = 4,
UCHAR_DEFAULT_IGNORABLE_CODE_POINT = 5,
UCHAR_DEPRECATED = 6,
UCHAR_DIACRITIC = 7,
UCHAR_EXTENDER = 8,
UCHAR_FULL_COMPOSITION_EXCLUSION = 9,
UCHAR_GRAPHEME_BASE = 10,
UCHAR_GRAPHEME_EXTEND = 11,
UCHAR_GRAPHEME_LINK = 12,
UCHAR_HEX_DIGIT = 13,
UCHAR_HYPHEN = 14,
UCHAR_ID_CONTINUE = 15,
UCHAR_ID_START = 16,
UCHAR_IDEOGRAPHIC = 17,
UCHAR_IDS_BINARY_OPERATOR = 18,
UCHAR_IDS_TRINARY_OPERATOR = 19,
UCHAR_JOIN_CONTROL = 20,
UCHAR_LOGICAL_ORDER_EXCEPTION = 21,
UCHAR_LOWERCASE = 22,
UCHAR_MATH = 23,
UCHAR_NONCHARACTER_CODE_POINT = 24,
UCHAR_QUOTATION_MARK = 25,
UCHAR_RADICAL = 26,
UCHAR_SOFT_DOTTED = 27,
UCHAR_TERMINAL_PUNCTUATION = 28,
UCHAR_UNIFIED_IDEOGRAPH = 29,
UCHAR_UPPERCASE = 30,
UCHAR_WHITE_SPACE = 31,
UCHAR_XID_CONTINUE = 32,
UCHAR_XID_START = 33,
UCHAR_CASE_SENSITIVE = 34,
UCHAR_S_TERM = 35,
UCHAR_VARIATION_SELECTOR = 36,
UCHAR_NFD_INERT = 37,
UCHAR_NFKD_INERT = 38,
UCHAR_NFC_INERT = 39,
UCHAR_NFKC_INERT = 40,
UCHAR_SEGMENT_STARTER = 41,
UCHAR_PATTERN_SYNTAX = 42,
UCHAR_PATTERN_WHITE_SPACE = 43,
UCHAR_POSIX_ALNUM = 44,
UCHAR_POSIX_BLANK = 45,
UCHAR_POSIX_GRAPH = 46,
UCHAR_POSIX_PRINT = 47,
UCHAR_POSIX_XDIGIT = 48,
UCHAR_CASED = 49,
UCHAR_CASE_IGNORABLE = 50,
UCHAR_CHANGES_WHEN_LOWERCASED = 51,
UCHAR_CHANGES_WHEN_UPPERCASED = 52,
UCHAR_CHANGES_WHEN_TITLECASED = 53,
UCHAR_CHANGES_WHEN_CASEFOLDED = 54,
UCHAR_CHANGES_WHEN_CASEMAPPED = 55,
UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED = 56,
UCHAR_EMOJI = 57,
UCHAR_EMOJI_PRESENTATION = 58,
UCHAR_EMOJI_MODIFIER = 59,
UCHAR_EMOJI_MODIFIER_BASE = 60,
UCHAR_EMOJI_COMPONENT = 61,
UCHAR_REGIONAL_INDICATOR = 62,
UCHAR_PREPENDED_CONCATENATION_MARK = 63,
UCHAR_EXTENDED_PICTOGRAPHIC = 64,
UCHAR_BASIC_EMOJI = 65,
UCHAR_EMOJI_KEYCAP_SEQUENCE = 66,
UCHAR_RGI_EMOJI_MODIFIER_SEQUENCE = 67,
UCHAR_RGI_EMOJI_FLAG_SEQUENCE = 68,
UCHAR_RGI_EMOJI_TAG_SEQUENCE = 69,
UCHAR_RGI_EMOJI_ZWJ_SEQUENCE = 70,
UCHAR_RGI_EMOJI = 71,
UCHAR_BINARY_LIMIT = 72,
UCHAR_BIDI_CLASS = 4096,
UCHAR_BLOCK = 4097,
UCHAR_CANONICAL_COMBINING_CLASS = 4098,
UCHAR_DECOMPOSITION_TYPE = 4099,
UCHAR_EAST_ASIAN_WIDTH = 4100,
UCHAR_GENERAL_CATEGORY = 4101,
UCHAR_JOINING_GROUP = 4102,
UCHAR_JOINING_TYPE = 4103,
UCHAR_LINE_BREAK = 4104,
UCHAR_NUMERIC_TYPE = 4105,
UCHAR_SCRIPT = 4106,
UCHAR_HANGUL_SYLLABLE_TYPE = 4107,
UCHAR_NFD_QUICK_CHECK = 4108,
UCHAR_NFKD_QUICK_CHECK = 4109,
UCHAR_NFC_QUICK_CHECK = 4110,
UCHAR_NFKC_QUICK_CHECK = 4111,
UCHAR_LEAD_CANONICAL_COMBINING_CLASS = 4112,
UCHAR_TRAIL_CANONICAL_COMBINING_CLASS = 4113,
UCHAR_GRAPHEME_CLUSTER_BREAK = 4114,
UCHAR_SENTENCE_BREAK = 4115,
UCHAR_WORD_BREAK = 4116,
UCHAR_BIDI_PAIRED_BRACKET_TYPE = 4117,
UCHAR_INDIC_POSITIONAL_CATEGORY = 4118,
UCHAR_INDIC_SYLLABIC_CATEGORY = 4119,
UCHAR_VERTICAL_ORIENTATION = 4120,
UCHAR_INT_LIMIT = 4121,
UCHAR_GENERAL_CATEGORY_MASK = 8192,
UCHAR_MASK_LIMIT = 8193,
UCHAR_NUMERIC_VALUE = 12288,
UCHAR_DOUBLE_LIMIT = 12289,
UCHAR_AGE = 16384,
UCHAR_BIDI_MIRRORING_GLYPH = 16385,
UCHAR_CASE_FOLDING = 16386,
UCHAR_ISO_COMMENT = 16387,
UCHAR_LOWERCASE_MAPPING = 16388,
UCHAR_NAME = 16389,
UCHAR_SIMPLE_CASE_FOLDING = 16390,
UCHAR_SIMPLE_LOWERCASE_MAPPING = 16391,
UCHAR_SIMPLE_TITLECASE_MAPPING = 16392,
UCHAR_SIMPLE_UPPERCASE_MAPPING = 16393,
UCHAR_TITLECASE_MAPPING = 16394,
UCHAR_UNICODE_1_NAME = 16395,
UCHAR_UPPERCASE_MAPPING = 16396,
UCHAR_BIDI_PAIRED_BRACKET = 16397,
UCHAR_STRING_LIMIT = 16398,
UCHAR_SCRIPT_EXTENSIONS = 28672,
UCHAR_OTHER_PROPERTY_LIMIT = 28673,
UCHAR_INVALID_CODE = -1,
}
impl UCharCategory {
pub const U_GENERAL_OTHER_TYPES: UCharCategory = UCharCategory::U_UNASSIGNED;
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharCategory {
U_UNASSIGNED = 0,
U_UPPERCASE_LETTER = 1,
U_LOWERCASE_LETTER = 2,
U_TITLECASE_LETTER = 3,
U_MODIFIER_LETTER = 4,
U_OTHER_LETTER = 5,
U_NON_SPACING_MARK = 6,
U_ENCLOSING_MARK = 7,
U_COMBINING_SPACING_MARK = 8,
U_DECIMAL_DIGIT_NUMBER = 9,
U_LETTER_NUMBER = 10,
U_OTHER_NUMBER = 11,
U_SPACE_SEPARATOR = 12,
U_LINE_SEPARATOR = 13,
U_PARAGRAPH_SEPARATOR = 14,
U_CONTROL_CHAR = 15,
U_FORMAT_CHAR = 16,
U_PRIVATE_USE_CHAR = 17,
U_SURROGATE = 18,
U_DASH_PUNCTUATION = 19,
U_START_PUNCTUATION = 20,
U_END_PUNCTUATION = 21,
U_CONNECTOR_PUNCTUATION = 22,
U_OTHER_PUNCTUATION = 23,
U_MATH_SYMBOL = 24,
U_CURRENCY_SYMBOL = 25,
U_MODIFIER_SYMBOL = 26,
U_OTHER_SYMBOL = 27,
U_INITIAL_PUNCTUATION = 28,
U_FINAL_PUNCTUATION = 29,
U_CHAR_CATEGORY_COUNT = 30,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharDirection {
U_LEFT_TO_RIGHT = 0,
U_RIGHT_TO_LEFT = 1,
U_EUROPEAN_NUMBER = 2,
U_EUROPEAN_NUMBER_SEPARATOR = 3,
U_EUROPEAN_NUMBER_TERMINATOR = 4,
U_ARABIC_NUMBER = 5,
U_COMMON_NUMBER_SEPARATOR = 6,
U_BLOCK_SEPARATOR = 7,
U_SEGMENT_SEPARATOR = 8,
U_WHITE_SPACE_NEUTRAL = 9,
U_OTHER_NEUTRAL = 10,
U_LEFT_TO_RIGHT_EMBEDDING = 11,
U_LEFT_TO_RIGHT_OVERRIDE = 12,
U_RIGHT_TO_LEFT_ARABIC = 13,
U_RIGHT_TO_LEFT_EMBEDDING = 14,
U_RIGHT_TO_LEFT_OVERRIDE = 15,
U_POP_DIRECTIONAL_FORMAT = 16,
U_DIR_NON_SPACING_MARK = 17,
U_BOUNDARY_NEUTRAL = 18,
U_FIRST_STRONG_ISOLATE = 19,
U_LEFT_TO_RIGHT_ISOLATE = 20,
U_RIGHT_TO_LEFT_ISOLATE = 21,
U_POP_DIRECTIONAL_ISOLATE = 22,
U_CHAR_DIRECTION_COUNT = 23,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCharNameChoice {
U_UNICODE_CHAR_NAME = 0,
U_UNICODE_10_CHAR_NAME = 1,
U_EXTENDED_CHAR_NAME = 2,
U_CHAR_NAME_ALIAS = 3,
U_CHAR_NAME_CHOICE_COUNT = 4,
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UPropertyNameChoice {
U_SHORT_PROPERTY_NAME = 0,
U_LONG_PROPERTY_NAME = 1,
U_PROPERTY_NAME_CHOICE_COUNT = 2,
}
unsafe extern "C" {
pub fn u_hasBinaryProperty_72(c: UChar32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_stringHasBinaryProperty_72(s: *const UChar, length: i32, which: UProperty) -> UBool;
}
unsafe extern "C" {
pub fn u_getBinaryPropertySet_72(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const USet;
}
unsafe extern "C" {
pub fn u_isUAlphabetic_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isULowercase_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUUppercase_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isUWhiteSpace_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_getIntPropertyValue_72(c: UChar32, which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMinValue_72(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMaxValue_72(which: UProperty) -> i32;
}
unsafe extern "C" {
pub fn u_getIntPropertyMap_72(
property: UProperty,
pErrorCode: *mut UErrorCode,
) -> *const UCPMap;
}
unsafe extern "C" {
pub fn u_getNumericValue_72(c: UChar32) -> f64;
}
unsafe extern "C" {
pub fn u_islower_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isupper_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_istitle_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdigit_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalpha_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isalnum_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isxdigit_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_ispunct_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isgraph_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isblank_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isdefined_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isspace_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaSpaceChar_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isWhitespace_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_iscntrl_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isISOControl_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isprint_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isbase_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charDirection_72(c: UChar32) -> UCharDirection;
}
unsafe extern "C" {
pub fn u_isMirrored_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_charMirror_72(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_getBidiPairedBracket_72(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_charType_72(c: UChar32) -> i8;
}
pub type UCharEnumTypeRange = ::std::option::Option<
unsafe extern "C" fn(
context: *const ::std::os::raw::c_void,
start: UChar32,
limit: UChar32,
type_: UCharCategory,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharTypes_72(
enumRange: UCharEnumTypeRange,
context: *const ::std::os::raw::c_void,
);
}
unsafe extern "C" {
pub fn u_getCombiningClass_72(c: UChar32) -> u8;
}
unsafe extern "C" {
pub fn u_charDigitValue_72(c: UChar32) -> i32;
}
unsafe extern "C" {
pub fn u_charName_72(
code: UChar32,
nameChoice: UCharNameChoice,
buffer: *mut ::std::os::raw::c_char,
bufferLength: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_getISOComment_72(
c: UChar32,
dest: *mut ::std::os::raw::c_char,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn u_charFromName_72(
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
pErrorCode: *mut UErrorCode,
) -> UChar32;
}
pub type UEnumCharNamesFn = ::std::option::Option<
unsafe extern "C" fn(
context: *mut ::std::os::raw::c_void,
code: UChar32,
nameChoice: UCharNameChoice,
name: *const ::std::os::raw::c_char,
length: i32,
) -> UBool,
>;
unsafe extern "C" {
pub fn u_enumCharNames_72(
start: UChar32,
limit: UChar32,
fn_: UEnumCharNamesFn,
context: *mut ::std::os::raw::c_void,
nameChoice: UCharNameChoice,
pErrorCode: *mut UErrorCode,
);
}
unsafe extern "C" {
pub fn u_getPropertyName_72(
property: UProperty,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyEnum_72(alias: *const ::std::os::raw::c_char) -> UProperty;
}
unsafe extern "C" {
pub fn u_getPropertyValueName_72(
property: UProperty,
value: i32,
nameChoice: UPropertyNameChoice,
) -> *const ::std::os::raw::c_char;
}
unsafe extern "C" {
pub fn u_getPropertyValueEnum_72(
property: UProperty,
alias: *const ::std::os::raw::c_char,
) -> i32;
}
unsafe extern "C" {
pub fn u_isIDStart_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDPart_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isIDIgnorable_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDStart_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_isJavaIDPart_72(c: UChar32) -> UBool;
}
unsafe extern "C" {
pub fn u_tolower_72(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_toupper_72(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_totitle_72(c: UChar32) -> UChar32;
}
unsafe extern "C" {
pub fn u_foldCase_72(c: UChar32, options: u32) -> UChar32;
}
unsafe extern "C" {
pub fn u_digit_72(ch: UChar32, radix: i8) -> i32;
}
unsafe extern "C" {
pub fn u_forDigit_72(digit: i32, radix: i8) -> UChar32;
}
unsafe extern "C" {
pub fn u_charAge_72(c: UChar32, versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getUnicodeVersion_72(versionArray: *mut u8);
}
unsafe extern "C" {
pub fn u_getFC_NFKC_Closure_72(
c: UChar32,
dest: *mut UChar,
destCapacity: i32,
pErrorCode: *mut UErrorCode,
) -> i32;
}
unsafe extern "C" {
pub fn utext_close_72(ut: *mut UText) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUTF8_72(
ut: *mut UText,
s: *const ::std::os::raw::c_char,
length: i64,
status: *mut UErrorCode,
) -> *mut UText;
}
unsafe extern "C" {
pub fn utext_openUChars_72(
ut: *mut UText,
s: *const UChar,
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | true |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/bindgen_special/lib_72.rs | rust_icu_sys/bindgen_special/lib_72.rs | /* automatically generated by rust-bindgen 0.59.1 */
pub type size_t = ::std::os::raw::c_ulong;
pub type __int8_t = ::std::os::raw::c_schar;
pub type __uint8_t = ::std::os::raw::c_uchar;
pub type __int16_t = ::std::os::raw::c_short;
pub type __uint16_t = ::std::os::raw::c_ushort;
pub type __int32_t = ::std::os::raw::c_int;
pub type __uint32_t = ::std::os::raw::c_uint;
pub type __off_t = ::std::os::raw::c_long;
pub type __off64_t = ::std::os::raw::c_long;
pub type FILE = _IO_FILE;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_marker {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_codecvt {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_wide_data {
_unused: [u8; 0],
}
pub type _IO_lock_t = ::std::os::raw::c_void;
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq)]
pub struct _IO_FILE {
pub _flags: ::std::os::raw::c_int,
pub _IO_read_ptr: *mut ::std::os::raw::c_char,
pub _IO_read_end: *mut ::std::os::raw::c_char,
pub _IO_read_base: *mut ::std::os::raw::c_char,
pub _IO_write_base: *mut ::std::os::raw::c_char,
pub _IO_write_ptr: *mut ::std::os::raw::c_char,
pub _IO_write_end: *mut ::std::os::raw::c_char,
pub _IO_buf_base: *mut ::std::os::raw::c_char,
pub _IO_buf_end: *mut ::std::os::raw::c_char,
pub _IO_save_base: *mut ::std::os::raw::c_char,
pub _IO_backup_base: *mut ::std::os::raw::c_char,
pub _IO_save_end: *mut ::std::os::raw::c_char,
pub _markers: *mut _IO_marker,
pub _chain: *mut _IO_FILE,
pub _fileno: ::std::os::raw::c_int,
pub _flags2: ::std::os::raw::c_int,
pub _old_offset: __off_t,
pub _cur_column: ::std::os::raw::c_ushort,
pub _vtable_offset: ::std::os::raw::c_schar,
pub _shortbuf: [::std::os::raw::c_char; 1usize],
pub _lock: *mut _IO_lock_t,
pub _offset: __off64_t,
pub _codecvt: *mut _IO_codecvt,
pub _wide_data: *mut _IO_wide_data,
pub _freeres_list: *mut _IO_FILE,
pub _freeres_buf: *mut ::std::os::raw::c_void,
pub __pad5: size_t,
pub _mode: ::std::os::raw::c_int,
pub _unused2: [::std::os::raw::c_char; 20usize],
}
#[test]
fn bindgen_test_layout__IO_FILE() {
assert_eq!(
::std::mem::size_of::<_IO_FILE>(),
216usize,
concat!("Size of: ", stringify!(_IO_FILE))
);
assert_eq!(
::std::mem::align_of::<_IO_FILE>(),
8usize,
concat!("Alignment of ", stringify!(_IO_FILE))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._flags as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_flags)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_ptr as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_ptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_end as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_base as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_base as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_ptr as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_ptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_end as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_buf_base as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_buf_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_buf_end as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_buf_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_save_base as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_save_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_backup_base as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_backup_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_save_end as *const _ as usize },
88usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_save_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._markers as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_markers)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._chain as *const _ as usize },
104usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_chain)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._fileno as *const _ as usize },
112usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_fileno)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._flags2 as *const _ as usize },
116usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_flags2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._old_offset as *const _ as usize },
120usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_old_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._cur_column as *const _ as usize },
128usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_cur_column)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._vtable_offset as *const _ as usize },
130usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_vtable_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._shortbuf as *const _ as usize },
131usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_shortbuf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._lock as *const _ as usize },
136usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._offset as *const _ as usize },
144usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._codecvt as *const _ as usize },
152usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_codecvt)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._wide_data as *const _ as usize },
160usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_wide_data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._freeres_list as *const _ as usize },
168usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_freeres_list)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._freeres_buf as *const _ as usize },
176usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_freeres_buf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad5 as *const _ as usize },
184usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad5)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._mode as *const _ as usize },
192usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_mode)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._unused2 as *const _ as usize },
196usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_unused2)
)
);
}
impl Default for _IO_FILE {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
pub type UBool = i8;
pub type UChar = u16;
pub type UChar32 = i32;
#[repr(C)]
#[derive(Copy, Clone)]pub union UCPTrieData { pub ptr0 : * const :: std :: os :: raw :: c_void , pub ptr16 : * const u16 , pub ptr32 : * const u32 , pub ptr8 : * const u8 , }#[test]
fn bindgen_test_layout_UCPTrieData() {
assert_eq!(
::std::mem::size_of::<UCPTrieData>(),
8usize,
concat!("Size of: ", stringify!(UCPTrieData))
);
assert_eq!(
::std::mem::align_of::<UCPTrieData>(),
8usize,
concat!("Alignment of ", stringify!(UCPTrieData))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrieData>())).ptr0 as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UCPTrieData),
"::",
stringify!(ptr0)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrieData>())).ptr16 as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UCPTrieData),
"::",
stringify!(ptr16)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrieData>())).ptr32 as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UCPTrieData),
"::",
stringify!(ptr32)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrieData>())).ptr8 as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UCPTrieData),
"::",
stringify!(ptr8)
)
);
}
impl Default for UCPTrieData {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct UCPTrie {
pub index: *const u16,
pub data: UCPTrieData,
pub indexLength: i32,
pub dataLength: i32,
pub highStart: UChar32,
pub shifted12HighStart: u16,
pub type_: i8,
pub valueWidth: i8,
pub reserved32: u32,
pub reserved16: u16,
pub index3NullOffset: u16,
pub dataNullOffset: i32,
pub nullValue: u32,
}
#[test]
fn bindgen_test_layout_UCPTrie() {
assert_eq!(
::std::mem::size_of::<UCPTrie>(),
48usize,
concat!("Size of: ", stringify!(UCPTrie))
);
assert_eq!(
::std::mem::align_of::<UCPTrie>(),
8usize,
concat!("Alignment of ", stringify!(UCPTrie))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).index as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).data as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).indexLength as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(indexLength)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).dataLength as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(dataLength)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).highStart as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(highStart)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).shifted12HighStart as *const _ as usize },
28usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(shifted12HighStart)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).type_ as *const _ as usize },
30usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).valueWidth as *const _ as usize },
31usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(valueWidth)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).reserved32 as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(reserved32)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).reserved16 as *const _ as usize },
36usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(reserved16)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).index3NullOffset as *const _ as usize },
38usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(index3NullOffset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).dataNullOffset as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(dataNullOffset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UCPTrie>())).nullValue as *const _ as usize },
44usize,
concat!(
"Offset of field: ",
stringify!(UCPTrie),
"::",
stringify!(nullValue)
)
);
}
impl Default for UCPTrie {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPTrieType {
UCPTRIE_TYPE_ANY = - 1,
UCPTRIE_TYPE_FAST = 0,
UCPTRIE_TYPE_SMALL = 1,
}
#[repr(i32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UCPTrieValueWidth {
UCPTRIE_VALUE_BITS_ANY = - 1,
UCPTRIE_VALUE_BITS_16 = 0,
UCPTRIE_VALUE_BITS_32 = 1,
UCPTRIE_VALUE_BITS_8 = 2,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct USet {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct UNewTrie2 {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq)]
pub struct UTrie2 {
pub index: *const u16,
pub data16: *const u16,
pub data32: *const u32,
pub indexLength: i32,
pub dataLength: i32,
pub index2NullOffset: u16,
pub dataNullOffset: u16,
pub initialValue: u32,
pub errorValue: u32,
pub highStart: UChar32,
pub highValueIndex: i32,
pub memory: *mut ::std::os::raw::c_void,
pub length: i32,
pub isMemoryOwned: UBool,
pub padding1: UBool,
pub padding2: i16,
pub newTrie: *mut UNewTrie2,
}
#[test]
fn bindgen_test_layout_UTrie2() {
assert_eq!(
::std::mem::size_of::<UTrie2>(),
80usize,
concat!("Size of: ", stringify!(UTrie2))
);
assert_eq!(
::std::mem::align_of::<UTrie2>(),
8usize,
concat!("Alignment of ", stringify!(UTrie2))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).index as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).data16 as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(data16)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).data32 as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(data32)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).indexLength as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(indexLength)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).dataLength as *const _ as usize },
28usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(dataLength)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).index2NullOffset as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(index2NullOffset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).dataNullOffset as *const _ as usize },
34usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(dataNullOffset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).initialValue as *const _ as usize },
36usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(initialValue)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).errorValue as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(errorValue)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).highStart as *const _ as usize },
44usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(highStart)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).highValueIndex as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(highValueIndex)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).memory as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(memory)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).length as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(length)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).isMemoryOwned as *const _ as usize },
68usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(isMemoryOwned)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).padding1 as *const _ as usize },
69usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(padding1)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).padding2 as *const _ as usize },
70usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(padding2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<UTrie2>())).newTrie as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(UTrie2),
"::",
stringify!(newTrie)
)
);
}
impl Default for UTrie2 {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(u32)]
#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Eq)]
pub enum UTargetSyntax {
UPRV_TARGET_SYNTAX_CCODE = 0,
UPRV_TARGET_SYNTAX_TOML = 1,
}
extern "C" {
pub fn usrc_create(
path: *const ::std::os::raw::c_char,
filename: *const ::std::os::raw::c_char,
copyrightYear: i32,
generator: *const ::std::os::raw::c_char,
) -> *mut FILE;
}
extern "C" {
pub fn usrc_createTextData(
path: *const ::std::os::raw::c_char,
filename: *const ::std::os::raw::c_char,
copyrightYear: i32,
generator: *const ::std::os::raw::c_char,
) -> *mut FILE;
}
extern "C" {
pub fn usrc_writeCopyrightHeader(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
copyrightYear: i32,
);
}
extern "C" {
pub fn usrc_writeFileNameGeneratedBy(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
filename: *const ::std::os::raw::c_char,
generator: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn usrc_writeArray(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
p: *const ::std::os::raw::c_void,
width: i32,
length: i32,
indent: *const ::std::os::raw::c_char,
postfix: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn usrc_writeUTrie2Arrays(
f: *mut FILE,
indexPrefix: *const ::std::os::raw::c_char,
dataPrefix: *const ::std::os::raw::c_char,
pTrie: *const UTrie2,
postfix: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn usrc_writeUTrie2Struct(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
pTrie: *const UTrie2,
indexName: *const ::std::os::raw::c_char,
dataName: *const ::std::os::raw::c_char,
postfix: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn usrc_writeUCPTrieArrays(
f: *mut FILE,
indexPrefix: *const ::std::os::raw::c_char,
dataPrefix: *const ::std::os::raw::c_char,
pTrie: *const UCPTrie,
postfix: *const ::std::os::raw::c_char,
syntax: UTargetSyntax,
);
}
extern "C" {
pub fn usrc_writeUCPTrieStruct(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
pTrie: *const UCPTrie,
indexName: *const ::std::os::raw::c_char,
dataName: *const ::std::os::raw::c_char,
postfix: *const ::std::os::raw::c_char,
syntax: UTargetSyntax,
);
}
extern "C" {
pub fn usrc_writeUCPTrie(
f: *mut FILE,
name: *const ::std::os::raw::c_char,
pTrie: *const UCPTrie,
syntax: UTargetSyntax,
);
}
extern "C" {
pub fn usrc_writeUnicodeSet(f: *mut FILE, pSet: *const USet, syntax: UTargetSyntax);
}
extern "C" {
pub fn usrc_writeArrayOfMostlyInvChars(
f: *mut FILE,
prefix: *const ::std::os::raw::c_char,
p: *const ::std::os::raw::c_char,
length: i32,
postfix: *const ::std::os::raw::c_char,
);
}
extern "C" {
pub fn usrc_writeStringAsASCII(
f: *mut FILE,
ptr: *const UChar,
length: i32,
syntax: UTargetSyntax,
);
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/src/lib.rs | rust_icu_sys/src/lib.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Notes:
// * deref_nullptr: since rustc 1.53, bindgen causes UB warnings -- see
// https://github.com/rust-lang/rust-bindgen/issues/1651 remove this once bindgen has fixed the
// issue (currently at version 1.59.1)
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals,
unused_imports,
rustdoc::bare_urls,
deref_nullptr
)]
#[cfg(all(feature = "icu_version_in_env", feature = "icu_config"))]
compile_error!(
"Features `icu_version_in_env` and `icu_config` are not compatible."
+ " Choose at most one of them."
);
#[cfg(all(feature = "icu_config", not(feature = "use-bindgen")))]
compile_error!("Feature `icu_config` is useless without the feature `use-bindgen`");
// This feature combination is not inherrently a problem; we had no use case that
// required it just yet.
#[cfg(all(not(feature = "renaming"), not(feature = "use-bindgen")))]
compile_error!("You must use `renaming` when not using `use-bindgen`");
#[cfg(feature = "use-bindgen")]
include!(concat!(env!("OUT_DIR"), "/macros.rs"));
#[cfg(all(
feature = "use-bindgen",
feature = "icu_config",
not(feature = "icu_version_in_env")
))]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));
#[cfg(not(feature = "use-bindgen"))]
include!("../bindgen/macros.rs");
#[cfg(all(
not(feature = "use-bindgen"),
not(feature = "icu_version_in_env"),
not(feature = "icu_config")
))]
include!("../bindgen/lib.rs");
#[cfg(all(
not(feature = "use-bindgen"),
feature = "icu_version_in_env",
not(feature = "icu_config")
))]
include!(concat!(
"../bindgen/lib_",
env!("RUST_ICU_MAJOR_VERSION_NUMBER"),
".rs"
));
// Add the ability to print the error code, so that it can be reported in
// aggregated errors.
impl std::fmt::Display for UErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
extern crate libc;
impl From<i8> for UCharCategory {
fn from(value: i8) -> Self {
match value {
0 => UCharCategory::U_UNASSIGNED,
1 => UCharCategory::U_UPPERCASE_LETTER,
2 => UCharCategory::U_LOWERCASE_LETTER,
3 => UCharCategory::U_TITLECASE_LETTER,
4 => UCharCategory::U_MODIFIER_LETTER,
5 => UCharCategory::U_OTHER_LETTER,
6 => UCharCategory::U_NON_SPACING_MARK,
7 => UCharCategory::U_ENCLOSING_MARK,
8 => UCharCategory::U_COMBINING_SPACING_MARK,
9 => UCharCategory::U_DECIMAL_DIGIT_NUMBER,
10 => UCharCategory::U_LETTER_NUMBER,
11 => UCharCategory::U_OTHER_NUMBER,
12 => UCharCategory::U_SPACE_SEPARATOR,
13 => UCharCategory::U_LINE_SEPARATOR,
14 => UCharCategory::U_PARAGRAPH_SEPARATOR,
15 => UCharCategory::U_CONTROL_CHAR,
16 => UCharCategory::U_FORMAT_CHAR,
17 => UCharCategory::U_PRIVATE_USE_CHAR,
18 => UCharCategory::U_SURROGATE,
19 => UCharCategory::U_DASH_PUNCTUATION,
20 => UCharCategory::U_START_PUNCTUATION,
21 => UCharCategory::U_END_PUNCTUATION,
22 => UCharCategory::U_CONNECTOR_PUNCTUATION,
23 => UCharCategory::U_OTHER_PUNCTUATION,
24 => UCharCategory::U_MATH_SYMBOL,
25 => UCharCategory::U_CURRENCY_SYMBOL,
26 => UCharCategory::U_MODIFIER_SYMBOL,
27 => UCharCategory::U_OTHER_SYMBOL,
28 => UCharCategory::U_INITIAL_PUNCTUATION,
29 => UCharCategory::U_FINAL_PUNCTUATION,
30 => UCharCategory::U_CHAR_CATEGORY_COUNT,
_ => {
panic!("could not convert: {}", value);
}
}
}
}
// Items used by the `versioned_function!` macro. Unstable private API; do not use.
#[doc(hidden)]
pub mod __private_do_not_use {
pub extern crate paste;
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_sys/tests/hygiene.rs | rust_icu_sys/tests/hygiene.rs | #![no_implicit_prelude]
#[test]
fn hygiene() {
let mut status = ::rust_icu_sys::UErrorCode::U_ZERO_ERROR;
unsafe { ::rust_icu_sys::versioned_function!(u_init)(&mut status) };
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
google/rust_icu | https://github.com/google/rust_icu/blob/acdee0b194d408c598b6d2f0ccf9d2b87204de87/rust_icu_intl/src/lib.rs | rust_icu_intl/src/lib.rs | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # ECMA 402 inspired APIs, based on Unicode's [ICU library](http://site.icu-project.org/home)
//!
//! This crate contains implementations of APIs with functionality analogous to those provided by
//! [ECMA 402](https://www.ecma-international.org/publications/standards/Ecma-402.htm) for
//! ECMAScript. The APIs are said to be *inspired* by ECMA 402, since ECMAScript constructs are
//! not idiomatic in rust. The differences should be minimal enough that the analogous
//! functionality is readily identified.
//!
//! The plural rules are taken verbatim from the ICU library that is pulled as a
//! dependency.
//!
//! # When to use this library
//!
//! The defining feature of this particular implementation of plural rules is that
//! it is based on the use of the ICU library. If you need feature parity with
//! C or C++ or Java programs on ICU behavior and do not want to bring in other
//! dependencies, you may want to use this crate.
//!
//! # Alternatives
//!
//! There are other implementations of this functionality for rust. Here are some,
//! but not necessarily all, different implementations:
//!
//! * [`intl_pluralrules`](https://crates.io/crates/intl_pluralrules): a library that parses the
//! plural rules from the [Unicode CLDR](http://cldr.unicode.org/) repository.
//!
//! # Example use
//!
//! ```
//! use rust_icu_uloc as uloc;
//! use rust_icu_intl as intl;
//! use std::convert::TryFrom;
//! let rules = intl::PluralRules::new(&uloc::ULoc::try_from("ar_EG").unwrap());
//! assert_eq!("zero", rules.select(0.0));
//! assert_eq!("one", rules.select(1.0));
//! assert_eq!("two", rules.select(2.0));
//! assert_eq!("few", rules.select(6.0));
//! assert_eq!("many", rules.select(18.0));
//! ```
use rust_icu_uloc as uloc;
use rust_icu_umsg::{self as umsg, message_format};
use rust_icu_ustring as ustring;
use std::convert::TryFrom;
/// Implements ECMA-402 `Intl.PluralRules` based on the ICU locale data.
pub struct PluralRules {
formatter: umsg::UMessageFormat,
}
// These responses convert a plural class into English text, which is exactly
// what needs to be reported by the "select" method.
static RESPONSES: &str = r#"{0,plural,
zero {zero}
one {one}
two {two}
few {few}
many {many}
other {other}}"#;
impl PluralRules {
/// Creates a new plural rules formatter.
pub fn new(locale: &uloc::ULoc) -> PluralRules {
let pattern = ustring::UChar::try_from(RESPONSES).expect("pattern should never fail");
let formatter = umsg::UMessageFormat::try_from(&pattern, &locale)
.expect("this formatter should never fail");
PluralRules { formatter }
}
/// For a given numeric selector returns the class of plural that is to be used with
/// this number in the language that [PluralRules] has been configured for.
///
/// Note that the argument `n` is *always* a floating point, because it allows you
/// to format expressions like "2.54 people on average".
///
/// Returns one of the following classes:
///
/// * `=n`: used for exact overrides, where `n` is a number; for example `=0`.
/// * `zero`: used for all "zero-like" numbers. Some languages may have zero-like
/// numbers that are not zero themselves.
///
pub fn select(&self, n: f64) -> String {
message_format!(self.formatter, { n => Double}).expect("should be formattable")
}
}
#[cfg(test)]
mod tests {
use super::*;
// Checks the rule and prints useful diagnostic messages in case of failure.
fn check_rule(expected: &str, n: f64, rules: &PluralRules) {
assert_eq!(expected, rules.select(n), "select({})", n);
}
#[test]
fn selection_for_ar_eg() -> Result<(), anyhow::Error> {
let rules = PluralRules::new(&uloc::ULoc::try_from("ar_EG")?);
check_rule("zero", 0.0, &rules);
check_rule("one", 1.0, &rules);
check_rule("two", 2.0, &rules);
check_rule("few", 6.0, &rules);
check_rule("many", 18.0, &rules);
Ok(())
}
#[test]
fn selection_for_sr_rs() -> Result<(), anyhow::Error> {
let rules = PluralRules::new(&uloc::ULoc::try_from("sr_RS")?);
check_rule("other", 0.0, &rules);
check_rule("one", 1.0, &rules);
check_rule("few", 2.0, &rules);
check_rule("few", 4.0, &rules);
check_rule("other", 5.0, &rules);
check_rule("other", 6.0, &rules);
check_rule("other", 18.0, &rules);
check_rule("other", 11.0, &rules);
check_rule("one", 21.0, &rules);
check_rule("few", 22.0, &rules);
check_rule("few", 24.0, &rules);
check_rule("other", 25.0, &rules);
check_rule("other", 26.0, &rules);
Ok(())
}
}
| rust | Apache-2.0 | acdee0b194d408c598b6d2f0ccf9d2b87204de87 | 2026-01-04T20:25:24.845005Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/lib.rs | src/lib.rs | //! # Async IMAP
//!
//! This crate lets you connect to and interact with servers
//! that implement the IMAP protocol ([RFC 3501](https://tools.ietf.org/html/rfc3501) and extensions).
//! After authenticating with the server,
//! IMAP lets you list, fetch, and search for e-mails,
//! as well as monitor mailboxes for changes.
//!
//! ## Connecting
//!
//! Connect to the server, for example using TLS connection on port 993
//! or plain TCP connection on port 143 if you plan to use STARTTLS.
//! can be used.
//! Pass the stream to [`Client::new()`].
//! This gives you an unauthenticated [`Client`].
//!
//! Then read the server greeting:
//! ```ignore
//! let _greeting = client
//! .read_response().await?
//! .expect("unexpected end of stream, expected greeting");
//! ```
//!
//! ## STARTTLS
//!
//! If you connected on a non-TLS port, upgrade the connection using STARTTLS:
//! ```ignore
//! client.run_command_and_check_ok("STARTTLS", None).await?;
//! let stream = client.into_inner();
//! ```
//! Convert this stream into a TLS stream using a library
//! such as [`async-native-tls`](https://crates.io/crates/async-native-tls)
//! or [Rustls](`https://crates.io/crates/rustls`).
//! Once you have a TLS stream, wrap it back into a [`Client`]:
//! ```ignore
//! let client = Client::new(tls_stream);
//! ```
//! Note that there is no server greeting after STARTTLS.
//!
//! ## Authentication and session usage
//!
//! Once you have an established connection,
//! authenticate using [`Client::login`] or [`Client::authenticate`]
//! to perform username/password or challenge/response authentication respectively.
//! This in turn gives you an authenticated
//! [`Session`], which lets you access the mailboxes at the server.
//! For example:
//! ```ignore
//! let mut session = client
//! .login("alice@example.org", "password").await
//! .map_err(|(err, _client)| err)?;
//! session.select("INBOX").await?;
//!
//! // Fetch message number 1 in this mailbox, along with its RFC 822 field.
//! // RFC 822 dictates the format of the body of e-mails.
//! let messages_stream = imap_session.fetch("1", "RFC822").await?;
//! let messages: Vec<_> = messages_stream.try_collect().await?;
//! let message = messages.first().expect("found no messages in the INBOX");
//!
//! // Extract the message body.
//! let body = message.body().expect("message did not have a body!");
//! let body = std::str::from_utf8(body)
//! .expect("message was not valid utf-8")
//! .to_string();
//!
//! session.logout().await?;
//! ```
//!
//! The documentation within this crate borrows heavily from the various RFCs,
//! but should not be considered a complete reference.
//! If anything is unclear,
//! follow the links to the RFCs embedded in the documentation
//! for the various types and methods and read the raw text there!
//!
//! See the `examples/` directory for usage examples.
#![warn(missing_docs)]
#![deny(rust_2018_idioms, unsafe_code)]
#[cfg(not(any(feature = "runtime-tokio", feature = "runtime-async-std")))]
compile_error!("one of 'runtime-async-std' or 'runtime-tokio' features must be enabled");
#[cfg(all(feature = "runtime-tokio", feature = "runtime-async-std"))]
compile_error!("only one of 'runtime-async-std' or 'runtime-tokio' features must be enabled");
#[macro_use]
extern crate pin_utils;
// Reexport imap_proto for easier access.
pub use imap_proto;
mod authenticator;
mod client;
pub mod error;
pub mod extensions;
mod imap_stream;
mod parse;
pub mod types;
#[cfg(feature = "compress")]
pub use crate::extensions::compress::DeflateStream;
pub use crate::authenticator::Authenticator;
pub use crate::client::*;
#[cfg(test)]
mod mock_stream;
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/parse.rs | src/parse.rs | use std::collections::HashSet;
use async_channel as channel;
use futures::io;
use futures::prelude::*;
use futures::stream::Stream;
use imap_proto::{self, MailboxDatum, Metadata, RequestId, Response};
use crate::error::{Error, Result};
use crate::types::ResponseData;
use crate::types::*;
pub(crate) fn parse_names<T: Stream<Item = io::Result<ResponseData>> + Unpin + Send>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> impl Stream<Item = Result<Name>> + '_ + Send + Unpin {
use futures::{FutureExt, StreamExt};
StreamExt::filter_map(
StreamExt::take_while(stream, move |res| filter(res, &command_tag)),
move |resp| {
let unsolicited = unsolicited.clone();
async move {
match resp {
Ok(resp) => match resp.parsed() {
Response::MailboxData(MailboxDatum::List { .. }) => {
let name = Name::from_mailbox_data(resp);
Some(Ok(name))
}
_ => {
handle_unilateral(resp, unsolicited);
None
}
},
Err(err) => Some(Err(err.into())),
}
}
.boxed()
},
)
}
pub(crate) fn filter(
res: &io::Result<ResponseData>,
command_tag: &RequestId,
) -> impl Future<Output = bool> {
let val = filter_sync(res, command_tag);
futures::future::ready(val)
}
pub(crate) fn filter_sync(res: &io::Result<ResponseData>, command_tag: &RequestId) -> bool {
match res {
Ok(res) => match res.parsed() {
Response::Done { tag, .. } => tag != command_tag,
_ => true,
},
Err(_err) => {
// Do not filter out the errors such as unexpected EOF.
true
}
}
}
pub(crate) fn parse_fetches<T: Stream<Item = io::Result<ResponseData>> + Unpin + Send>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> impl Stream<Item = Result<Fetch>> + '_ + Send + Unpin {
use futures::{FutureExt, StreamExt};
StreamExt::filter_map(
StreamExt::take_while(stream, move |res| filter(res, &command_tag)),
move |resp| {
let unsolicited = unsolicited.clone();
async move {
match resp {
Ok(resp) => match resp.parsed() {
Response::Fetch(..) => Some(Ok(Fetch::new(resp))),
_ => {
handle_unilateral(resp, unsolicited);
None
}
},
Err(err) => Some(Err(err.into())),
}
}
.boxed()
},
)
}
pub(crate) async fn parse_status<T: Stream<Item = io::Result<ResponseData>> + Unpin + Send>(
stream: &mut T,
expected_mailbox: &str,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Mailbox> {
let mut mbox = Mailbox::default();
while let Some(resp) = stream.try_next().await? {
match resp.parsed() {
Response::Done {
tag,
status,
code,
information,
..
} if tag == &command_tag => {
use imap_proto::Status;
match status {
Status::Ok => {
break;
}
Status::Bad => {
return Err(Error::Bad(format!("code: {code:?}, info: {information:?}")))
}
Status::No => {
return Err(Error::No(format!("code: {code:?}, info: {information:?}")))
}
_ => {
return Err(Error::Io(io::Error::other(format!(
"status: {status:?}, code: {code:?}, information: {information:?}"
))));
}
}
}
Response::MailboxData(MailboxDatum::Status { mailbox, status })
if mailbox == expected_mailbox =>
{
for attribute in status {
match attribute {
StatusAttribute::HighestModSeq(highest_modseq) => {
mbox.highest_modseq = Some(*highest_modseq)
}
StatusAttribute::Messages(exists) => mbox.exists = *exists,
StatusAttribute::Recent(recent) => mbox.recent = *recent,
StatusAttribute::UidNext(uid_next) => mbox.uid_next = Some(*uid_next),
StatusAttribute::UidValidity(uid_validity) => {
mbox.uid_validity = Some(*uid_validity)
}
StatusAttribute::Unseen(unseen) => mbox.unseen = Some(*unseen),
_ => {}
}
}
}
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(mbox)
}
pub(crate) fn parse_expunge<T: Stream<Item = io::Result<ResponseData>> + Unpin + Send>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> impl Stream<Item = Result<u32>> + '_ + Send {
use futures::StreamExt;
StreamExt::filter_map(
StreamExt::take_while(stream, move |res| filter(res, &command_tag)),
move |resp| {
let unsolicited = unsolicited.clone();
async move {
match resp {
Ok(resp) => match resp.parsed() {
Response::Expunge(id) => Some(Ok(*id)),
_ => {
handle_unilateral(resp, unsolicited);
None
}
},
Err(err) => Some(Err(err.into())),
}
}
},
)
}
pub(crate) async fn parse_capabilities<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Capabilities> {
let mut caps: HashSet<Capability> = HashSet::new();
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
Response::Capabilities(cs) => {
for c in cs {
caps.insert(Capability::from(c)); // TODO: avoid clone
}
}
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(Capabilities(caps))
}
pub(crate) async fn parse_noop<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<()> {
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
handle_unilateral(resp, unsolicited.clone());
}
Ok(())
}
pub(crate) async fn parse_mailbox<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Mailbox> {
let mut mailbox = Mailbox::default();
while let Some(resp) = stream.try_next().await? {
match resp.parsed() {
Response::Done {
tag,
status,
code,
information,
..
} if tag == &command_tag => {
use imap_proto::Status;
match status {
Status::Ok => {
break;
}
Status::Bad => {
return Err(Error::Bad(format!("code: {code:?}, info: {information:?}")))
}
Status::No => {
return Err(Error::No(format!("code: {code:?}, info: {information:?}")))
}
_ => {
return Err(Error::Io(io::Error::other(format!(
"status: {status:?}, code: {code:?}, information: {information:?}"
))));
}
}
}
Response::Data {
status,
code,
information,
} => {
use imap_proto::Status;
match status {
Status::Ok => {
use imap_proto::ResponseCode;
match code {
Some(ResponseCode::UidValidity(uid)) => {
mailbox.uid_validity = Some(*uid);
}
Some(ResponseCode::UidNext(unext)) => {
mailbox.uid_next = Some(*unext);
}
Some(ResponseCode::HighestModSeq(highest_modseq)) => {
mailbox.highest_modseq = Some(*highest_modseq);
}
Some(ResponseCode::Unseen(n)) => {
mailbox.unseen = Some(*n);
}
Some(ResponseCode::PermanentFlags(flags)) => {
mailbox
.permanent_flags
.extend(flags.iter().map(|s| (*s).to_string()).map(Flag::from));
}
_ => {}
}
}
Status::Bad => {
return Err(Error::Bad(format!("code: {code:?}, info: {information:?}")))
}
Status::No => {
return Err(Error::No(format!("code: {code:?}, info: {information:?}")))
}
_ => {
return Err(Error::Io(io::Error::other(format!(
"status: {status:?}, code: {code:?}, information: {information:?}"
))));
}
}
}
Response::MailboxData(m) => match m {
MailboxDatum::Status { .. } => handle_unilateral(resp, unsolicited.clone()),
MailboxDatum::Exists(e) => {
mailbox.exists = *e;
}
MailboxDatum::Recent(r) => {
mailbox.recent = *r;
}
MailboxDatum::Flags(flags) => {
mailbox
.flags
.extend(flags.iter().map(|s| (*s).to_string()).map(Flag::from));
}
MailboxDatum::List { .. } => {}
MailboxDatum::MetadataSolicited { .. } => {}
MailboxDatum::MetadataUnsolicited { .. } => {}
MailboxDatum::Search { .. } => {}
MailboxDatum::Sort { .. } => {}
_ => {}
},
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(mailbox)
}
pub(crate) async fn parse_ids<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<HashSet<u32>> {
let mut ids: HashSet<u32> = HashSet::new();
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
Response::MailboxData(MailboxDatum::Search(cs)) => {
for c in cs {
ids.insert(*c);
}
}
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(ids)
}
/// Parses [GETMETADATA](https://www.rfc-editor.org/info/rfc5464) response.
pub(crate) async fn parse_metadata<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
mailbox_name: &str,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Vec<Metadata>> {
let mut res_values = Vec::new();
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
// METADATA Response with Values
// <https://datatracker.ietf.org/doc/html/rfc5464.html#section-4.4.1>
Response::MailboxData(MailboxDatum::MetadataSolicited { mailbox, values })
if mailbox == mailbox_name =>
{
res_values.extend_from_slice(values.as_slice());
}
// We are not interested in
// [Unsolicited METADATA Response without Values](https://datatracker.ietf.org/doc/html/rfc5464.html#section-4.4.2),
// they go to unsolicited channel with other unsolicited responses.
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(res_values)
}
/// Sends unilateral server response
/// (see Section 7 of RFC 3501)
/// into the channel.
///
/// If the channel is full or closed,
/// i.e. the responses are not being consumed,
/// ignores new responses.
pub(crate) fn handle_unilateral(
res: ResponseData,
unsolicited: channel::Sender<UnsolicitedResponse>,
) {
match res.parsed() {
Response::MailboxData(MailboxDatum::Status { mailbox, status }) => {
unsolicited
.try_send(UnsolicitedResponse::Status {
mailbox: (mailbox.as_ref()).into(),
attributes: status.to_vec(),
})
.ok();
}
Response::MailboxData(MailboxDatum::Recent(n)) => {
unsolicited.try_send(UnsolicitedResponse::Recent(*n)).ok();
}
Response::MailboxData(MailboxDatum::Exists(n)) => {
unsolicited.try_send(UnsolicitedResponse::Exists(*n)).ok();
}
Response::Expunge(n) => {
unsolicited.try_send(UnsolicitedResponse::Expunge(*n)).ok();
}
_ => {
unsolicited.try_send(UnsolicitedResponse::Other(res)).ok();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_channel::bounded;
use bytes::BytesMut;
fn input_stream(data: &[&str]) -> Vec<io::Result<ResponseData>> {
data.iter()
.map(|line| {
let block = BytesMut::from(line.as_bytes());
ResponseData::try_new(block, |bytes| -> io::Result<_> {
let (remaining, response) = imap_proto::parser::parse_response(bytes).unwrap();
assert_eq!(remaining.len(), 0);
Ok(response)
})
})
.collect()
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_capability_test() {
let expected_capabilities = &["IMAP4rev1", "STARTTLS", "AUTH=GSSAPI", "LOGINDISABLED"];
let responses =
input_stream(&["* CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI LOGINDISABLED\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let (send, recv) = bounded(10);
let id = RequestId("A0001".into());
let capabilities = parse_capabilities(&mut stream, send, id).await.unwrap();
// shouldn't be any unexpected responses parsed
assert!(recv.is_empty());
assert_eq!(capabilities.len(), 4);
for e in expected_capabilities {
assert!(capabilities.has_str(e));
}
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_capability_case_insensitive_test() {
// Test that "IMAP4REV1" (instead of "IMAP4rev1") is accepted
let expected_capabilities = &["IMAP4rev1", "STARTTLS"];
let responses = input_stream(&["* CAPABILITY IMAP4REV1 STARTTLS\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let (send, recv) = bounded(10);
let id = RequestId("A0001".into());
let capabilities = parse_capabilities(&mut stream, send, id).await.unwrap();
// shouldn't be any unexpected responses parsed
assert!(recv.is_empty());
assert_eq!(capabilities.len(), 2);
for e in expected_capabilities {
assert!(capabilities.has_str(e));
}
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[should_panic]
async fn parse_capability_invalid_test() {
let (send, recv) = bounded(10);
let responses = input_stream(&["* JUNK IMAP4rev1 STARTTLS AUTH=GSSAPI LOGINDISABLED\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
parse_capabilities(&mut stream, send.clone(), id)
.await
.unwrap();
assert!(recv.is_empty());
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_names_test() {
let (send, recv) = bounded(10);
let responses = input_stream(&["* LIST (\\HasNoChildren) \".\" \"INBOX\"\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
let names: Vec<_> = parse_names(&mut stream, send, id)
.try_collect::<Vec<Name>>()
.await
.unwrap();
assert!(recv.is_empty());
assert_eq!(names.len(), 1);
assert_eq!(
names[0].attributes(),
&[NameAttribute::Extension("\\HasNoChildren".into())]
);
assert_eq!(names[0].delimiter(), Some("."));
assert_eq!(names[0].name(), "INBOX");
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_fetches_empty() {
let (send, recv) = bounded(10);
let responses = input_stream(&[]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("a".into());
let fetches = parse_fetches(&mut stream, send, id)
.try_collect::<Vec<_>>()
.await
.unwrap();
assert!(recv.is_empty());
assert!(fetches.is_empty());
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_fetches_test() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"* 24 FETCH (FLAGS (\\Seen) UID 4827943)\r\n",
"* 25 FETCH (FLAGS (\\Seen))\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("a".into());
let fetches = parse_fetches(&mut stream, send, id)
.try_collect::<Vec<_>>()
.await
.unwrap();
assert!(recv.is_empty());
assert_eq!(fetches.len(), 2);
assert_eq!(fetches[0].message, 24);
assert_eq!(fetches[0].flags().collect::<Vec<_>>(), vec![Flag::Seen]);
assert_eq!(fetches[0].uid, Some(4827943));
assert_eq!(fetches[0].body(), None);
assert_eq!(fetches[0].header(), None);
assert_eq!(fetches[1].message, 25);
assert_eq!(fetches[1].flags().collect::<Vec<_>>(), vec![Flag::Seen]);
assert_eq!(fetches[1].uid, None);
assert_eq!(fetches[1].body(), None);
assert_eq!(fetches[1].header(), None);
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_fetches_w_unilateral() {
// https://github.com/mattnenterprise/rust-imap/issues/81
let (send, recv) = bounded(10);
let responses = input_stream(&["* 37 FETCH (UID 74)\r\n", "* 1 RECENT\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("a".into());
let fetches = parse_fetches(&mut stream, send, id)
.try_collect::<Vec<_>>()
.await
.unwrap();
assert_eq!(recv.recv().await.unwrap(), UnsolicitedResponse::Recent(1));
assert_eq!(fetches.len(), 1);
assert_eq!(fetches[0].message, 37);
assert_eq!(fetches[0].uid, Some(74));
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_names_w_unilateral() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"* LIST (\\HasNoChildren) \".\" \"INBOX\"\r\n",
"* 4 EXPUNGE\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
let names = parse_names(&mut stream, send, id)
.try_collect::<Vec<_>>()
.await
.unwrap();
assert_eq!(recv.recv().await.unwrap(), UnsolicitedResponse::Expunge(4));
assert_eq!(names.len(), 1);
assert_eq!(
names[0].attributes(),
&[NameAttribute::Extension("\\HasNoChildren".into())]
);
assert_eq!(names[0].delimiter(), Some("."));
assert_eq!(names[0].name(), "INBOX");
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_capabilities_w_unilateral() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"* CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI LOGINDISABLED\r\n",
"* STATUS dev.github (MESSAGES 10 UIDNEXT 11 UIDVALIDITY 1408806928 UNSEEN 0)\r\n",
"* 4 EXISTS\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let expected_capabilities = &["IMAP4rev1", "STARTTLS", "AUTH=GSSAPI", "LOGINDISABLED"];
let id = RequestId("A0001".into());
let capabilities = parse_capabilities(&mut stream, send, id).await.unwrap();
assert_eq!(capabilities.len(), 4);
for e in expected_capabilities {
assert!(capabilities.has_str(e));
}
assert_eq!(
recv.recv().await.unwrap(),
UnsolicitedResponse::Status {
mailbox: "dev.github".to_string(),
attributes: vec![
StatusAttribute::Messages(10),
StatusAttribute::UidNext(11),
StatusAttribute::UidValidity(1408806928),
StatusAttribute::Unseen(0)
]
}
);
assert_eq!(recv.recv().await.unwrap(), UnsolicitedResponse::Exists(4));
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_ids_w_unilateral() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"* SEARCH 23 42 4711\r\n",
"* 1 RECENT\r\n",
"* STATUS INBOX (MESSAGES 10 UIDNEXT 11 UIDVALIDITY 1408806928 UNSEEN 0)\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
let ids = parse_ids(&mut stream, send, id).await.unwrap();
assert_eq!(ids, [23, 42, 4711].iter().cloned().collect());
assert_eq!(recv.recv().await.unwrap(), UnsolicitedResponse::Recent(1));
assert_eq!(
recv.recv().await.unwrap(),
UnsolicitedResponse::Status {
mailbox: "INBOX".to_string(),
attributes: vec![
StatusAttribute::Messages(10),
StatusAttribute::UidNext(11),
StatusAttribute::UidValidity(1408806928),
StatusAttribute::Unseen(0)
]
}
);
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_ids_test() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"* SEARCH 1600 1698 1739 1781 1795 1885 1891 1892 1893 1898 1899 1901 1911 1926 1932 1933 1993 1994 2007 2032 2033 2041 2053 2062 2063 2065 2066 2072 2078 2079 2082 2084 2095 2100 2101 2102 2103 2104 2107 2116 2120 2135 2138 2154 2163 2168 2172 2189 2193 2198 2199 2205 2212 2213 2221 2227 2267 2275 2276 2295 2300 2328 2330 2332 2333 2334\r\n",
"* SEARCH 2335 2336 2337 2338 2339 2341 2342 2347 2349 2350 2358 2359 2362 2369 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2390 2392 2397 2400 2401 2403 2405 2409 2411 2414 2417 2419 2420 2424 2426 2428 2439 2454 2456 2467 2468 2469 2490 2515 2519 2520 2521\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
let ids = parse_ids(&mut stream, send, id).await.unwrap();
assert!(recv.is_empty());
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert_eq!(
ids,
[
1600, 1698, 1739, 1781, 1795, 1885, 1891, 1892, 1893, 1898, 1899, 1901, 1911, 1926,
1932, 1933, 1993, 1994, 2007, 2032, 2033, 2041, 2053, 2062, 2063, 2065, 2066, 2072,
2078, 2079, 2082, 2084, 2095, 2100, 2101, 2102, 2103, 2104, 2107, 2116, 2120, 2135,
2138, 2154, 2163, 2168, 2172, 2189, 2193, 2198, 2199, 2205, 2212, 2213, 2221, 2227,
2267, 2275, 2276, 2295, 2300, 2328, 2330, 2332, 2333, 2334, 2335, 2336, 2337, 2338,
2339, 2341, 2342, 2347, 2349, 2350, 2358, 2359, 2362, 2369, 2371, 2372, 2373, 2374,
2375, 2376, 2377, 2378, 2379, 2380, 2381, 2382, 2383, 2384, 2385, 2386, 2390, 2392,
2397, 2400, 2401, 2403, 2405, 2409, 2411, 2414, 2417, 2419, 2420, 2424, 2426, 2428,
2439, 2454, 2456, 2467, 2468, 2469, 2490, 2515, 2519, 2520, 2521
]
.iter()
.cloned()
.collect()
);
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_ids_search() {
let (send, recv) = bounded(10);
let responses = input_stream(&["* SEARCH\r\n"]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0001".into());
let ids = parse_ids(&mut stream, send, id).await.unwrap();
assert!(recv.is_empty());
let ids: HashSet<u32> = ids.iter().cloned().collect();
assert_eq!(ids, HashSet::<u32>::new());
}
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn parse_mailbox_does_not_exist_error() {
let (send, recv) = bounded(10);
let responses = input_stream(&[
"A0003 NO Mailbox doesn't exist: DeltaChat (0.001 + 0.140 + 0.139 secs).\r\n",
]);
let mut stream = async_std::stream::from_iter(responses);
let id = RequestId("A0003".into());
let mailbox = parse_mailbox(&mut stream, send, id).await;
assert!(recv.is_empty());
assert!(matches!(mailbox, Err(Error::No(_))));
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/client.rs | src/client.rs | use std::collections::{HashMap, HashSet};
use std::fmt;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::str;
use async_channel::{self as channel, bounded};
#[cfg(feature = "runtime-async-std")]
use async_std::io::{Read, Write, WriteExt};
use base64::Engine as _;
use extensions::id::{format_identification, parse_id};
use extensions::quota::parse_get_quota_root;
use futures::{io, Stream, TryStreamExt};
use imap_proto::{Metadata, RequestId, Response};
#[cfg(feature = "runtime-tokio")]
use tokio::io::{AsyncRead as Read, AsyncWrite as Write, AsyncWriteExt};
use super::authenticator::Authenticator;
use super::error::{Error, ParseError, Result, ValidateError};
use super::parse::*;
use super::types::*;
use crate::extensions::{self, quota::parse_get_quota};
use crate::imap_stream::ImapStream;
macro_rules! quote {
($x:expr) => {
format!("\"{}\"", $x.replace(r"\", r"\\").replace("\"", "\\\""))
};
}
/// An authenticated IMAP session providing the usual IMAP commands. This type is what you get from
/// a succesful login attempt.
///
/// Note that the server *is* allowed to unilaterally send things to the client for messages in
/// a selected mailbox whose status has changed. See the note on [unilateral server responses
/// in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7). Any such messages are parsed out
/// and sent on `Session::unsolicited_responses`.
// Both `Client` and `Session` deref to [`Connection`](struct.Connection.html), the underlying
// primitives type.
#[derive(Debug)]
pub struct Session<T: Read + Write + Unpin + fmt::Debug> {
pub(crate) conn: Connection<T>,
pub(crate) unsolicited_responses_tx: channel::Sender<UnsolicitedResponse>,
/// Server responses that are not related to the current command. See also the note on
/// [unilateral server responses in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7).
pub unsolicited_responses: channel::Receiver<UnsolicitedResponse>,
}
impl<T: Read + Write + Unpin + fmt::Debug> Unpin for Session<T> {}
impl<T: Read + Write + Unpin + fmt::Debug> Unpin for Client<T> {}
impl<T: Read + Write + Unpin + fmt::Debug> Unpin for Connection<T> {}
// Make it possible to access the inner connection and modify its settings, such as read/write
// timeouts.
impl<T: Read + Write + Unpin + fmt::Debug> AsMut<T> for Session<T> {
fn as_mut(&mut self) -> &mut T {
self.conn.stream.as_mut()
}
}
/// An (unauthenticated) handle to talk to an IMAP server.
///
/// This is what you get when first
/// connecting. A succesfull call to [`Client::login`] or [`Client::authenticate`] will return a
/// [`Session`] instance that provides the usual IMAP methods.
// Both `Client` and `Session` deref to [`Connection`](struct.Connection.html), the underlying
// primitives type.
#[derive(Debug)]
pub struct Client<T: Read + Write + Unpin + fmt::Debug> {
conn: Connection<T>,
}
/// The underlying primitives type. Both `Client`(unauthenticated) and `Session`(after succesful
/// login) use a `Connection` internally for the TCP stream primitives.
#[derive(Debug)]
pub struct Connection<T: Read + Write + Unpin + fmt::Debug> {
pub(crate) stream: ImapStream<T>,
/// Manages the request ids.
pub(crate) request_ids: IdGenerator,
}
// `Deref` instances are so we can make use of the same underlying primitives in `Client` and
// `Session`
impl<T: Read + Write + Unpin + fmt::Debug> Deref for Client<T> {
type Target = Connection<T>;
fn deref(&self) -> &Connection<T> {
&self.conn
}
}
impl<T: Read + Write + Unpin + fmt::Debug> DerefMut for Client<T> {
fn deref_mut(&mut self) -> &mut Connection<T> {
&mut self.conn
}
}
impl<T: Read + Write + Unpin + fmt::Debug> Deref for Session<T> {
type Target = Connection<T>;
fn deref(&self) -> &Connection<T> {
&self.conn
}
}
impl<T: Read + Write + Unpin + fmt::Debug> DerefMut for Session<T> {
fn deref_mut(&mut self) -> &mut Connection<T> {
&mut self.conn
}
}
// As the pattern of returning the unauthenticated `Client` (a.k.a. `self`) back with a login error
// is relatively common, it's abstacted away into a macro here.
//
// Note: 1) using `.map_err(|e| (e, self))` or similar here makes the closure own self, so we can't
// do that.
// 2) in theory we wouldn't need the second parameter, and could just use the identifier
// `self` from the surrounding function, but being explicit here seems a lot cleaner.
macro_rules! ok_or_unauth_client_err {
($r:expr, $self:expr) => {
match $r {
Ok(o) => o,
Err(e) => return Err((e.into(), $self)),
}
};
}
impl<T: Read + Write + Unpin + fmt::Debug + Send> Client<T> {
/// Creates a new client over the given stream.
///
/// This method primarily exists for writing tests that mock the underlying transport, but can
/// also be used to support IMAP over custom tunnels.
pub fn new(stream: T) -> Client<T> {
let stream = ImapStream::new(stream);
Client {
conn: Connection {
stream,
request_ids: IdGenerator::new(),
},
}
}
/// Convert this Client into the raw underlying stream.
pub fn into_inner(self) -> T {
let Self { conn, .. } = self;
conn.into_inner()
}
/// Log in to the IMAP server. Upon success a [`Session`](struct.Session.html) instance is
/// returned; on error the original `Client` instance is returned in addition to the error.
/// This is because `login` takes ownership of `self`, so in order to try again (e.g. after
/// prompting the user for credetials), ownership of the original `Client` needs to be
/// transferred back to the caller.
///
/// ```ignore
/// # fn main() -> async_imap::error::Result<()> {
/// # async_std::task::block_on(async {
///
/// let tls = async_native_tls::TlsConnector::new();
/// let client = async_imap::connect(
/// ("imap.example.org", 993),
/// "imap.example.org",
/// tls
/// ).await?;
///
/// match client.login("user", "pass").await {
/// Ok(s) => {
/// // you are successfully authenticated!
/// },
/// Err((e, orig_client)) => {
/// eprintln!("error logging in: {}", e);
/// // prompt user and try again with orig_client here
/// return Err(e);
/// }
/// }
///
/// # Ok(())
/// # }) }
/// ```
pub async fn login<U: AsRef<str>, P: AsRef<str>>(
mut self,
username: U,
password: P,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
let u = ok_or_unauth_client_err!(validate_str(username.as_ref()), self);
let p = ok_or_unauth_client_err!(validate_str(password.as_ref()), self);
ok_or_unauth_client_err!(
self.run_command_and_check_ok(&format!("LOGIN {u} {p}"), None)
.await,
self
);
Ok(Session::new(self.conn))
}
/// Authenticate with the server using the given custom `authenticator` to handle the server's
/// challenge.
///
/// ```ignore
/// struct OAuth2 {
/// user: String,
/// access_token: String,
/// }
///
/// impl async_imap::Authenticator for &OAuth2 {
/// type Response = String;
/// fn process(&mut self, _: &[u8]) -> Self::Response {
/// format!(
/// "user={}\x01auth=Bearer {}\x01\x01",
/// self.user, self.access_token
/// )
/// }
/// }
///
/// # fn main() -> async_imap::error::Result<()> {
/// # async_std::task::block_on(async {
///
/// let auth = OAuth2 {
/// user: String::from("me@example.com"),
/// access_token: String::from("<access_token>"),
/// };
///
/// let domain = "imap.example.com";
/// let tls = async_native_tls::TlsConnector::new();
/// let client = async_imap::connect((domain, 993), domain, tls).await?;
/// match client.authenticate("XOAUTH2", &auth).await {
/// Ok(session) => {
/// // you are successfully authenticated!
/// },
/// Err((err, orig_client)) => {
/// eprintln!("error authenticating: {}", err);
/// // prompt user and try again with orig_client here
/// return Err(err);
/// }
/// };
/// # Ok(())
/// # }) }
/// ```
pub async fn authenticate<A: Authenticator, S: AsRef<str>>(
mut self,
auth_type: S,
authenticator: A,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
let id = ok_or_unauth_client_err!(
self.run_command(&format!("AUTHENTICATE {}", auth_type.as_ref()))
.await,
self
);
let session = self.do_auth_handshake(id, authenticator).await?;
Ok(session)
}
/// This func does the handshake process once the authenticate command is made.
async fn do_auth_handshake<A: Authenticator>(
mut self,
id: RequestId,
mut authenticator: A,
) -> ::std::result::Result<Session<T>, (Error, Client<T>)> {
// explicit match blocks neccessary to convert error to tuple and not bind self too
// early (see also comment on `login`)
loop {
let Some(res) = ok_or_unauth_client_err!(self.read_response().await, self) else {
return Err((Error::ConnectionLost, self));
};
match res.parsed() {
Response::Continue { information, .. } => {
let challenge = if let Some(text) = information {
ok_or_unauth_client_err!(
base64::engine::general_purpose::STANDARD
.decode(text.as_ref())
.map_err(|e| Error::Parse(ParseError::Authentication(
(*text).to_string(),
Some(e)
))),
self
)
} else {
Vec::new()
};
let raw_response = &mut authenticator.process(&challenge);
let auth_response =
base64::engine::general_purpose::STANDARD.encode(raw_response);
ok_or_unauth_client_err!(
self.conn.run_command_untagged(&auth_response).await,
self
);
}
_ => {
ok_or_unauth_client_err!(self.check_done_ok_from(&id, None, res).await, self);
return Ok(Session::new(self.conn));
}
}
}
}
}
impl<T: Read + Write + Unpin + fmt::Debug + Send> Session<T> {
unsafe_pinned!(conn: Connection<T>);
pub(crate) fn get_stream(self: Pin<&mut Self>) -> Pin<&mut ImapStream<T>> {
self.conn().stream()
}
// not public, just to avoid duplicating the channel creation code
fn new(conn: Connection<T>) -> Self {
let (tx, rx) = bounded(100);
Session {
conn,
unsolicited_responses: rx,
unsolicited_responses_tx: tx,
}
}
/// Selects a mailbox.
///
/// The `SELECT` command selects a mailbox so that messages in the mailbox can be accessed.
/// Note that earlier versions of this protocol only required the FLAGS, EXISTS, and RECENT
/// untagged data; consequently, client implementations SHOULD implement default behavior for
/// missing data as discussed with the individual item.
///
/// Only one mailbox can be selected at a time in a connection; simultaneous access to multiple
/// mailboxes requires multiple connections. The `SELECT` command automatically deselects any
/// currently selected mailbox before attempting the new selection. Consequently, if a mailbox
/// is selected and a `SELECT` command that fails is attempted, no mailbox is selected.
///
/// Note that the server *is* allowed to unilaterally send things to the client for messages in
/// a selected mailbox whose status has changed. See the note on [unilateral server responses
/// in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7). This means that if run commands,
/// you *may* see additional untagged `RECENT`, `EXISTS`, `FETCH`, and `EXPUNGE` responses.
/// You can get them from the `unsolicited_responses` channel of the [`Session`](struct.Session.html).
pub async fn select<S: AsRef<str>>(&mut self, mailbox_name: S) -> Result<Mailbox> {
// TODO: also note READ/WRITE vs READ-only mode!
let id = self
.run_command(&format!("SELECT {}", validate_str(mailbox_name.as_ref())?))
.await?;
let mbox = parse_mailbox(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
)
.await?;
Ok(mbox)
}
/// Selects a mailbox with `(CONDSTORE)` parameter as defined in
/// [RFC 7162](https://www.rfc-editor.org/rfc/rfc7162.html#section-3.1.8).
pub async fn select_condstore<S: AsRef<str>>(&mut self, mailbox_name: S) -> Result<Mailbox> {
let id = self
.run_command(&format!(
"SELECT {} (CONDSTORE)",
validate_str(mailbox_name.as_ref())?
))
.await?;
let mbox = parse_mailbox(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
)
.await?;
Ok(mbox)
}
/// The `EXAMINE` command is identical to [`Session::select`] and returns the same output;
/// however, the selected mailbox is identified as read-only. No changes to the permanent state
/// of the mailbox, including per-user state, will happen in a mailbox opened with `examine`;
/// in particular, messagess cannot lose [`Flag::Recent`] in an examined mailbox.
pub async fn examine<S: AsRef<str>>(&mut self, mailbox_name: S) -> Result<Mailbox> {
let id = self
.run_command(&format!("EXAMINE {}", validate_str(mailbox_name.as_ref())?))
.await?;
let mbox = parse_mailbox(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
)
.await?;
Ok(mbox)
}
/// Fetch retreives data associated with a set of messages in the mailbox.
///
/// Note that the server *is* allowed to unilaterally include `FETCH` responses for other
/// messages in the selected mailbox whose status has changed. See the note on [unilateral
/// server responses in RFC 3501](https://tools.ietf.org/html/rfc3501#section-7).
///
/// `query` is a list of "data items" (space-separated in parentheses if `>1`). There are three
/// "macro items" which specify commonly-used sets of data items, and can be used instead of
/// data items. A macro must be used by itself, and not in conjunction with other macros or
/// data items. They are:
///
/// - `ALL`: equivalent to: `(FLAGS INTERNALDATE RFC822.SIZE ENVELOPE)`
/// - `FAST`: equivalent to: `(FLAGS INTERNALDATE RFC822.SIZE)`
///
/// The currently defined data items that can be fetched are listen [in the
/// RFC](https://tools.ietf.org/html/rfc3501#section-6.4.5), but here are some common ones:
///
/// - `FLAGS`: The flags that are set for this message.
/// - `INTERNALDATE`: The internal date of the message.
/// - `BODY[<section>]`:
///
/// The text of a particular body section. The section specification is a set of zero or
/// more part specifiers delimited by periods. A part specifier is either a part number
/// (see RFC) or one of the following: `HEADER`, `HEADER.FIELDS`, `HEADER.FIELDS.NOT`,
/// `MIME`, and `TEXT`. An empty section specification (i.e., `BODY[]`) refers to the
/// entire message, including the header.
///
/// The `HEADER`, `HEADER.FIELDS`, and `HEADER.FIELDS.NOT` part specifiers refer to the
/// [RFC-2822](https://tools.ietf.org/html/rfc2822) header of the message or of an
/// encapsulated [MIME-IMT](https://tools.ietf.org/html/rfc2046)
/// MESSAGE/[RFC822](https://tools.ietf.org/html/rfc822) message. `HEADER.FIELDS` and
/// `HEADER.FIELDS.NOT` are followed by a list of field-name (as defined in
/// [RFC-2822](https://tools.ietf.org/html/rfc2822)) names, and return a subset of the
/// header. The subset returned by `HEADER.FIELDS` contains only those header fields with
/// a field-name that matches one of the names in the list; similarly, the subset returned
/// by `HEADER.FIELDS.NOT` contains only the header fields with a non-matching field-name.
/// The field-matching is case-insensitive but otherwise exact. Subsetting does not
/// exclude the [RFC-2822](https://tools.ietf.org/html/rfc2822) delimiting blank line
/// between the header and the body; the blank line is included in all header fetches,
/// except in the case of a message which has no body and no blank line.
///
/// The `MIME` part specifier refers to the [MIME-IMB](https://tools.ietf.org/html/rfc2045)
/// header for this part.
///
/// The `TEXT` part specifier refers to the text body of the message,
/// omitting the [RFC-2822](https://tools.ietf.org/html/rfc2822) header.
///
/// [`Flag::Seen`] is implicitly set when `BODY` is fetched; if this causes the flags to
/// change, they will generally be included as part of the `FETCH` responses.
/// - `BODY.PEEK[<section>]`: An alternate form of `BODY[<section>]` that does not implicitly
/// set [`Flag::Seen`].
/// - `ENVELOPE`: The envelope structure of the message. This is computed by the server by
/// parsing the [RFC-2822](https://tools.ietf.org/html/rfc2822) header into the component
/// parts, defaulting various fields as necessary.
/// - `RFC822`: Functionally equivalent to `BODY[]`.
/// - `RFC822.HEADER`: Functionally equivalent to `BODY.PEEK[HEADER]`.
/// - `RFC822.SIZE`: The [RFC-2822](https://tools.ietf.org/html/rfc2822) size of the message.
/// - `UID`: The unique identifier for the message.
pub async fn fetch<S1, S2>(
&mut self,
sequence_set: S1,
query: S2,
) -> Result<impl Stream<Item = Result<Fetch>> + '_ + Send>
where
S1: AsRef<str>,
S2: AsRef<str>,
{
let id = self
.run_command(&format!(
"FETCH {} {}",
sequence_set.as_ref(),
query.as_ref()
))
.await?;
let res = parse_fetches(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
);
Ok(res)
}
/// Equivalent to [`Session::fetch`], except that all identifiers in `uid_set` are
/// [`Uid`]s. See also the [`UID` command](https://tools.ietf.org/html/rfc3501#section-6.4.8).
pub async fn uid_fetch<S1, S2>(
&mut self,
uid_set: S1,
query: S2,
) -> Result<impl Stream<Item = Result<Fetch>> + '_ + Send + Unpin>
where
S1: AsRef<str>,
S2: AsRef<str>,
{
let id = self
.run_command(&format!(
"UID FETCH {} {}",
uid_set.as_ref(),
query.as_ref()
))
.await?;
let res = parse_fetches(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
);
Ok(res)
}
/// Noop always succeeds, and it does nothing.
pub async fn noop(&mut self) -> Result<()> {
let id = self.run_command("NOOP").await?;
parse_noop(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
)
.await?;
Ok(())
}
/// Logout informs the server that the client is done with the connection.
pub async fn logout(&mut self) -> Result<()> {
self.run_command_and_check_ok("LOGOUT").await?;
Ok(())
}
/// The [`CREATE` command](https://tools.ietf.org/html/rfc3501#section-6.3.3) creates a mailbox
/// with the given name. `Ok` is returned only if a new mailbox with that name has been
/// created. It is an error to attempt to create `INBOX` or a mailbox with a name that
/// refers to an extant mailbox. Any error in creation will return [`Error::No`].
///
/// If the mailbox name is suffixed with the server's hierarchy separator character (as
/// returned from the server by [`Session::list`]), this is a declaration that the client
/// intends to create mailbox names under this name in the hierarchy. Servers that do not
/// require this declaration will ignore the declaration. In any case, the name created is
/// without the trailing hierarchy delimiter.
///
/// If the server's hierarchy separator character appears elsewhere in the name, the server
/// will generally create any superior hierarchical names that are needed for the `CREATE`
/// command to be successfully completed. In other words, an attempt to create `foo/bar/zap`
/// on a server in which `/` is the hierarchy separator character will usually create `foo/`
/// and `foo/bar/` if they do not already exist.
///
/// If a new mailbox is created with the same name as a mailbox which was deleted, its unique
/// identifiers will be greater than any unique identifiers used in the previous incarnation of
/// the mailbox UNLESS the new incarnation has a different unique identifier validity value.
/// See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
pub async fn create<S: AsRef<str>>(&mut self, mailbox_name: S) -> Result<()> {
self.run_command_and_check_ok(&format!("CREATE {}", validate_str(mailbox_name.as_ref())?))
.await?;
Ok(())
}
/// The [`DELETE` command](https://tools.ietf.org/html/rfc3501#section-6.3.4) permanently
/// removes the mailbox with the given name. `Ok` is returned only if the mailbox has been
/// deleted. It is an error to attempt to delete `INBOX` or a mailbox name that does not
/// exist.
///
/// The `DELETE` command will not remove inferior hierarchical names. For example, if a mailbox
/// `foo` has an inferior `foo.bar` (assuming `.` is the hierarchy delimiter character),
/// removing `foo` will not remove `foo.bar`. It is an error to attempt to delete a name that
/// has inferior hierarchical names and also has [`NameAttribute::NoSelect`].
///
/// It is permitted to delete a name that has inferior hierarchical names and does not have
/// [`NameAttribute::NoSelect`]. In this case, all messages in that mailbox are removed, and
/// the name will acquire [`NameAttribute::NoSelect`].
///
/// The value of the highest-used unique identifier of the deleted mailbox will be preserved so
/// that a new mailbox created with the same name will not reuse the identifiers of the former
/// incarnation, UNLESS the new incarnation has a different unique identifier validity value.
/// See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
pub async fn delete<S: AsRef<str>>(&mut self, mailbox_name: S) -> Result<()> {
self.run_command_and_check_ok(&format!("DELETE {}", validate_str(mailbox_name.as_ref())?))
.await?;
Ok(())
}
/// The [`RENAME` command](https://tools.ietf.org/html/rfc3501#section-6.3.5) changes the name
/// of a mailbox. `Ok` is returned only if the mailbox has been renamed. It is an error to
/// attempt to rename from a mailbox name that does not exist or to a mailbox name that already
/// exists. Any error in renaming will return [`Error::No`].
///
/// If the name has inferior hierarchical names, then the inferior hierarchical names will also
/// be renamed. For example, a rename of `foo` to `zap` will rename `foo/bar` (assuming `/` is
/// the hierarchy delimiter character) to `zap/bar`.
///
/// If the server's hierarchy separator character appears in the name, the server will
/// generally create any superior hierarchical names that are needed for the `RENAME` command
/// to complete successfully. In other words, an attempt to rename `foo/bar/zap` to
/// `baz/rag/zowie` on a server in which `/` is the hierarchy separator character will
/// generally create `baz/` and `baz/rag/` if they do not already exist.
///
/// The value of the highest-used unique identifier of the old mailbox name will be preserved
/// so that a new mailbox created with the same name will not reuse the identifiers of the
/// former incarnation, UNLESS the new incarnation has a different unique identifier validity
/// value. See the description of the [`UID`
/// command](https://tools.ietf.org/html/rfc3501#section-6.4.8) for more detail.
///
/// Renaming `INBOX` is permitted, and has special behavior. It moves all messages in `INBOX`
/// to a new mailbox with the given name, leaving `INBOX` empty. If the server implementation
/// supports inferior hierarchical names of `INBOX`, these are unaffected by a rename of
/// `INBOX`.
pub async fn rename<S1: AsRef<str>, S2: AsRef<str>>(&mut self, from: S1, to: S2) -> Result<()> {
self.run_command_and_check_ok(&format!(
"RENAME {} {}",
quote!(from.as_ref()),
quote!(to.as_ref())
))
.await?;
Ok(())
}
/// The [`SUBSCRIBE` command](https://tools.ietf.org/html/rfc3501#section-6.3.6) adds the
/// specified mailbox name to the server's set of "active" or "subscribed" mailboxes as
/// returned by [`Session::lsub`]. This command returns `Ok` only if the subscription is
/// successful.
///
/// The server may validate the mailbox argument to `SUBSCRIBE` to verify that it exists.
/// However, it will not unilaterally remove an existing mailbox name from the subscription
/// list even if a mailbox by that name no longer exists.
pub async fn subscribe<S: AsRef<str>>(&mut self, mailbox: S) -> Result<()> {
self.run_command_and_check_ok(&format!("SUBSCRIBE {}", quote!(mailbox.as_ref())))
.await?;
Ok(())
}
/// The [`UNSUBSCRIBE` command](https://tools.ietf.org/html/rfc3501#section-6.3.7) removes the
/// specified mailbox name from the server's set of "active" or "subscribed" mailboxes as
/// returned by [`Session::lsub`]. This command returns `Ok` only if the unsubscription is
/// successful.
pub async fn unsubscribe<S: AsRef<str>>(&mut self, mailbox: S) -> Result<()> {
self.run_command_and_check_ok(&format!("UNSUBSCRIBE {}", quote!(mailbox.as_ref())))
.await?;
Ok(())
}
/// The [`CAPABILITY` command](https://tools.ietf.org/html/rfc3501#section-6.1.1) requests a
/// listing of capabilities that the server supports. The server will include "IMAP4rev1" as
/// one of the listed capabilities. See [`Capabilities`] for further details.
pub async fn capabilities(&mut self) -> Result<Capabilities> {
let id = self.run_command("CAPABILITY").await?;
let c = parse_capabilities(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
)
.await?;
Ok(c)
}
/// The [`EXPUNGE` command](https://tools.ietf.org/html/rfc3501#section-6.4.3) permanently
/// removes all messages that have [`Flag::Deleted`] set from the currently selected mailbox.
/// The message sequence number of each message that is removed is returned.
pub async fn expunge(&mut self) -> Result<impl Stream<Item = Result<Seq>> + '_ + Send> {
let id = self.run_command("EXPUNGE").await?;
let res = parse_expunge(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
);
Ok(res)
}
/// The [`UID EXPUNGE` command](https://tools.ietf.org/html/rfc4315#section-2.1) permanently
/// removes all messages that both have [`Flag::Deleted`] set and have a [`Uid`] that is
/// included in the specified sequence set from the currently selected mailbox. If a message
/// either does not have [`Flag::Deleted`] set or has a [`Uid`] that is not included in the
/// specified sequence set, it is not affected.
///
/// This command is particularly useful for disconnected use clients. By using `uid_expunge`
/// instead of [`Self::expunge`] when resynchronizing with the server, the client can ensure that it
/// does not inadvertantly remove any messages that have been marked as [`Flag::Deleted`] by
/// other clients between the time that the client was last connected and the time the client
/// resynchronizes.
///
/// This command requires that the server supports [RFC
/// 4315](https://tools.ietf.org/html/rfc4315) as indicated by the `UIDPLUS` capability (see
/// [`Session::capabilities`]). If the server does not support the `UIDPLUS` capability, the
/// client should fall back to using [`Session::store`] to temporarily remove [`Flag::Deleted`]
/// from messages it does not want to remove, then invoking [`Session::expunge`]. Finally, the
/// client should use [`Session::store`] to restore [`Flag::Deleted`] on the messages in which
/// it was temporarily removed.
///
/// Alternatively, the client may fall back to using just [`Session::expunge`], risking the
/// unintended removal of some messages.
pub async fn uid_expunge<S: AsRef<str>>(
&mut self,
uid_set: S,
) -> Result<impl Stream<Item = Result<Uid>> + '_ + Send> {
let id = self
.run_command(&format!("UID EXPUNGE {}", uid_set.as_ref()))
.await?;
let res = parse_expunge(
&mut self.conn.stream,
self.unsolicited_responses_tx.clone(),
id,
);
Ok(res)
}
/// The [`CHECK` command](https://tools.ietf.org/html/rfc3501#section-6.4.1) requests a
/// checkpoint of the currently selected mailbox. A checkpoint refers to any
/// implementation-dependent housekeeping associated with the mailbox (e.g., resolving the
/// server's in-memory state of the mailbox with the state on its disk) that is not normally
/// executed as part of each command. A checkpoint MAY take a non-instantaneous amount of real
/// time to complete. If a server implementation has no such housekeeping considerations,
/// [`Session::check`] is equivalent to [`Session::noop`].
///
/// There is no guarantee that an `EXISTS` untagged response will happen as a result of
/// `CHECK`. [`Session::noop`] SHOULD be used for new message polling.
pub async fn check(&mut self) -> Result<()> {
self.run_command_and_check_ok("CHECK").await?;
Ok(())
}
/// The [`CLOSE` command](https://tools.ietf.org/html/rfc3501#section-6.4.2) permanently
/// removes all messages that have [`Flag::Deleted`] set from the currently selected mailbox,
/// and returns to the authenticated state from the selected state. No `EXPUNGE` responses are
/// sent.
///
/// No messages are removed, and no error is given, if the mailbox is selected by
/// [`Session::examine`] or is otherwise selected read-only.
///
/// Even if a mailbox is selected, [`Session::select`], [`Session::examine`], or
/// [`Session::logout`] command MAY be issued without previously invoking [`Session::close`].
/// [`Session::select`], [`Session::examine`], and [`Session::logout`] implicitly close the
/// currently selected mailbox without doing an expunge. However, when many messages are
/// deleted, a `CLOSE-LOGOUT` or `CLOSE-SELECT` sequence is considerably faster than an
/// `EXPUNGE-LOGOUT` or `EXPUNGE-SELECT` because no `EXPUNGE` responses (which the client would
/// probably ignore) are sent.
pub async fn close(&mut self) -> Result<()> {
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | true |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/error.rs | src/error.rs | //! IMAP error types.
use std::io::Error as IoError;
use std::str::Utf8Error;
use base64::DecodeError;
/// A convenience wrapper around `Result` for `imap::Error`.
pub type Result<T> = std::result::Result<T, Error>;
/// A set of errors that can occur in the IMAP client
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
/// An `io::Error` that occurred while trying to read or write to a network stream.
#[error("io: {0}")]
Io(#[from] IoError),
/// A BAD response from the IMAP server.
#[error("bad response: {0}")]
Bad(String),
/// A NO response from the IMAP server.
#[error("no response: {0}")]
No(String),
/// The connection was terminated unexpectedly.
#[error("connection lost")]
ConnectionLost,
/// Error parsing a server response.
#[error("parse: {0}")]
Parse(#[from] ParseError),
/// Command inputs were not valid [IMAP
/// strings](https://tools.ietf.org/html/rfc3501#section-4.3).
#[error("validate: {0}")]
Validate(#[from] ValidateError),
/// Error appending an e-mail.
#[error("could not append mail to mailbox")]
Append,
}
/// An error occured while trying to parse a server response.
#[derive(thiserror::Error, Debug)]
pub enum ParseError {
/// Indicates an error parsing the status response. Such as OK, NO, and BAD.
#[error("unable to parse status response")]
Invalid(Vec<u8>),
/// An unexpected response was encountered.
#[error("encountered unexpected parsed response: {0}")]
Unexpected(String),
/// The client could not find or decode the server's authentication challenge.
#[error("unable to parse authentication response: {0} - {1:?}")]
Authentication(String, Option<DecodeError>),
/// The client received data that was not UTF-8 encoded.
#[error("unable to parse data ({0:?}) as UTF-8 text: {1:?}")]
DataNotUtf8(Vec<u8>, #[source] Utf8Error),
/// The expected response for X was not found
#[error("expected response not found for: {0}")]
ExpectedResponseNotFound(String),
}
/// An [invalid character](https://tools.ietf.org/html/rfc3501#section-4.3) was found in an input
/// string.
#[derive(thiserror::Error, Debug)]
#[error("invalid character in input: '{0}'")]
pub struct ValidateError(pub char);
#[cfg(test)]
mod tests {
use super::*;
fn is_send<T: Send>(_t: T) {}
#[test]
fn test_send() {
is_send::<Result<usize>>(Ok(3));
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/mock_stream.rs | src/mock_stream.rs | use std::cmp::min;
use std::io::{Error, ErrorKind, Result};
use std::pin::Pin;
use std::task::{Context, Poll};
#[cfg(feature = "runtime-async-std")]
use async_std::io::{Read, Write};
#[cfg(feature = "runtime-tokio")]
use tokio::io::{AsyncRead as Read, AsyncWrite as Write};
#[derive(Default, Clone, Debug, Eq, PartialEq, Hash)]
pub struct MockStream {
read_buf: Vec<u8>,
read_pos: usize,
pub written_buf: Vec<u8>,
err_on_read: bool,
eof_on_read: bool,
read_delay: usize,
}
impl MockStream {
pub fn new(read_buf: Vec<u8>) -> MockStream {
MockStream::default().with_buf(read_buf)
}
pub fn with_buf(mut self, read_buf: Vec<u8>) -> MockStream {
self.read_buf = read_buf;
self
}
pub fn with_eof(mut self) -> MockStream {
self.eof_on_read = true;
self
}
pub fn with_err(mut self) -> MockStream {
self.err_on_read = true;
self
}
pub fn with_delay(mut self) -> MockStream {
self.read_delay = 1;
self
}
}
#[cfg(feature = "runtime-tokio")]
impl Read for MockStream {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<Result<()>> {
if self.eof_on_read {
return Poll::Ready(Ok(()));
}
if self.err_on_read {
return Poll::Ready(Err(Error::new(ErrorKind::Other, "MockStream Error")));
}
if self.read_pos >= self.read_buf.len() {
return Poll::Ready(Err(Error::new(ErrorKind::UnexpectedEof, "EOF")));
}
let mut write_len = min(buf.remaining(), self.read_buf.len() - self.read_pos);
if self.read_delay > 0 {
self.read_delay -= 1;
write_len = min(write_len, 1);
}
let max_pos = self.read_pos + write_len;
buf.put_slice(&self.read_buf[self.read_pos..max_pos]);
self.read_pos += write_len;
Poll::Ready(Ok(()))
}
}
#[cfg(feature = "runtime-tokio")]
impl Write for MockStream {
fn poll_write(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
self.written_buf.extend_from_slice(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Poll::Ready(Ok(()))
}
}
#[cfg(feature = "runtime-async-std")]
impl Read for MockStream {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize>> {
if self.eof_on_read {
return Poll::Ready(Ok(0));
}
if self.err_on_read {
return Poll::Ready(Err(Error::other("MockStream Error")));
}
if self.read_pos >= self.read_buf.len() {
return Poll::Ready(Err(Error::new(ErrorKind::UnexpectedEof, "EOF")));
}
let mut write_len = min(buf.len(), self.read_buf.len() - self.read_pos);
if self.read_delay > 0 {
self.read_delay -= 1;
write_len = min(write_len, 1);
}
let max_pos = self.read_pos + write_len;
for x in self.read_pos..max_pos {
buf[x - self.read_pos] = self.read_buf[x];
}
self.read_pos += write_len;
Poll::Ready(Ok(write_len))
}
}
#[cfg(feature = "runtime-async-std")]
impl Write for MockStream {
fn poll_write(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize>> {
self.written_buf.extend_from_slice(buf);
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
Poll::Ready(Ok(()))
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/imap_stream.rs | src/imap_stream.rs | use std::fmt;
use std::pin::Pin;
#[cfg(feature = "runtime-async-std")]
use async_std::io::{Read, Write, WriteExt};
use bytes::BytesMut;
use futures::stream::Stream;
use futures::task::{Context, Poll};
use futures::{io, ready};
use nom::Needed;
#[cfg(feature = "runtime-tokio")]
use tokio::io::{AsyncRead as Read, AsyncWrite as Write, AsyncWriteExt};
use crate::types::{Request, ResponseData};
/// Wraps a stream, and parses incoming data as imap server messages. Writes outgoing data
/// as imap client messages.
#[derive(Debug)]
pub struct ImapStream<R: Read + Write> {
/// The underlying stream
pub(crate) inner: R,
/// Number of bytes the next decode operation needs if known.
/// If the buffer contains less than this, it is a waste of time to try to parse it.
/// If unknown, set it to 0, so decoding is always attempted.
decode_needs: usize,
/// The buffer.
buffer: Buffer,
/// True if the stream should not return any more items.
///
/// This is set when reading from a stream
/// returns an error.
/// Afterwards the stream returns only `None`
/// and `poll_next()` does not read
/// from the underlying stream.
read_closed: bool,
}
impl<R: Read + Write + Unpin> ImapStream<R> {
/// Creates a new `ImapStream` based on the given `Read`er.
pub fn new(inner: R) -> Self {
ImapStream {
inner,
buffer: Buffer::new(),
decode_needs: 0,
read_closed: false,
}
}
pub async fn encode(&mut self, msg: Request) -> Result<(), io::Error> {
log::trace!(
"encode: input: {:?}, {:?}",
msg.0,
std::str::from_utf8(&msg.1)
);
if let Some(tag) = msg.0 {
self.inner.write_all(tag.as_bytes()).await?;
self.inner.write_all(b" ").await?;
}
self.inner.write_all(&msg.1).await?;
self.inner.write_all(b"\r\n").await?;
Ok(())
}
/// Gets a reference to the underlying stream.
pub fn get_ref(&self) -> &R {
&self.inner
}
/// Gets a mutable reference to the underlying stream.
pub fn get_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Returns underlying stream.
pub fn into_inner(self) -> R {
self.inner
}
/// Flushes the underlying stream.
pub async fn flush(&mut self) -> Result<(), io::Error> {
self.inner.flush().await
}
pub fn as_mut(&mut self) -> &mut R {
&mut self.inner
}
/// Attempts to decode a single response from the buffer.
///
/// Returns `None` if the buffer does not contain enough data.
fn decode(&mut self) -> io::Result<Option<ResponseData>> {
if self.buffer.used() < self.decode_needs {
// We know that there is not enough data to decode anything
// from previous attempts.
return Ok(None);
}
let block = self.buffer.take_block();
// Be aware, now self.buffer is invalid until block is returned or reset!
let res = ResponseData::try_new_or_recover(block, |buf| {
let buf = &buf[..self.buffer.used()];
log::trace!("decode: input: {:?}", std::str::from_utf8(buf));
match imap_proto::parser::parse_response(buf) {
Ok((remaining, response)) => {
// TODO: figure out if we can use a minimum required size for a response.
self.decode_needs = 0;
self.buffer.reset_with_data(remaining);
Ok(response)
}
Err(nom::Err::Incomplete(Needed::Size(min))) => {
log::trace!("decode: incomplete data, need minimum {min} bytes");
self.decode_needs = self.buffer.used() + usize::from(min);
Err(None)
}
Err(nom::Err::Incomplete(_)) => {
log::trace!("decode: incomplete data, need unknown number of bytes");
self.decode_needs = 0;
Err(None)
}
Err(other) => {
self.decode_needs = 0;
Err(Some(io::Error::other(format!(
"{:?} during parsing of {:?}",
other,
String::from_utf8_lossy(buf)
))))
}
}
});
match res {
Ok(response) => Ok(Some(response)),
Err((heads, err)) => {
self.buffer.return_block(heads);
match err {
Some(err) => Err(err),
None => Ok(None),
}
}
}
}
fn do_poll_next(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<io::Result<ResponseData>>> {
let this = &mut *self;
if let Some(response) = this.decode()? {
return Poll::Ready(Some(Ok(response)));
}
loop {
this.buffer.ensure_capacity(this.decode_needs)?;
let buf = this.buffer.free_as_mut_slice();
// The buffer should have at least one byte free
// before we try reading into it
// so we can treat 0 bytes read as EOF.
// This is guaranteed by `ensure_capacity()` above
// even if it is called with 0 as an argument.
debug_assert!(!buf.is_empty());
#[cfg(feature = "runtime-async-std")]
let num_bytes_read = ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?;
#[cfg(feature = "runtime-tokio")]
let num_bytes_read = {
let buf = &mut tokio::io::ReadBuf::new(buf);
let start = buf.filled().len();
ready!(Pin::new(&mut this.inner).poll_read(cx, buf))?;
buf.filled().len() - start
};
if num_bytes_read == 0 {
if this.buffer.used() > 0 {
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"bytes remaining in stream",
))));
}
return Poll::Ready(None);
}
this.buffer.extend_used(num_bytes_read);
if let Some(response) = this.decode()? {
return Poll::Ready(Some(Ok(response)));
}
}
}
}
/// Abstraction around needed buffer management.
struct Buffer {
/// The buffer itself.
block: BytesMut,
/// Offset where used bytes range ends.
offset: usize,
}
impl Buffer {
const BLOCK_SIZE: usize = 1024 * 4;
const MAX_CAPACITY: usize = 512 * 1024 * 1024; // 512 MiB
fn new() -> Self {
Self {
block: BytesMut::zeroed(Self::BLOCK_SIZE),
offset: 0,
}
}
/// Returns the number of bytes in the buffer containing data.
fn used(&self) -> usize {
self.offset
}
/// Returns the unused part of the buffer to which new data can be written.
fn free_as_mut_slice(&mut self) -> &mut [u8] {
&mut self.block[self.offset..]
}
/// Indicate how many new bytes were written into the buffer.
///
/// When new bytes are written into the slice returned by [`free_as_mut_slice`] this method
/// should be called to extend the used portion of the buffer to include the new data.
///
/// You can not write past the end of the buffer, so extending more then there is free
/// space marks the entire buffer as used.
///
/// [`free_as_mut_slice`]: Self::free_as_mut_slice
// aka advance()?
fn extend_used(&mut self, num_bytes: usize) {
self.offset += num_bytes;
if self.offset > self.block.len() {
self.offset = self.block.len();
}
}
/// Ensure the buffer has free capacity, optionally ensuring minimum buffer size.
fn ensure_capacity(&mut self, required: usize) -> io::Result<()> {
let free_bytes: usize = self.block.len() - self.offset;
let extra_bytes_needed: usize = required.saturating_sub(self.block.len());
if free_bytes == 0 || extra_bytes_needed > 0 {
let increase = std::cmp::max(Buffer::BLOCK_SIZE, extra_bytes_needed);
self.grow(increase)?;
}
// Assert that the buffer at least one free byte.
debug_assert!(self.offset < self.block.len());
// Assert that the buffer has at least the required capacity.
debug_assert!(self.block.len() >= required);
Ok(())
}
/// Grows the buffer, ensuring there are free bytes in the tail.
///
/// The specified number of bytes is only a minimum. The buffer could grow by more as
/// it will always grow in multiples of [`BLOCK_SIZE`].
///
/// If the size would be larger than [`MAX_CAPACITY`] an error is returned.
///
/// [`BLOCK_SIZE`]: Self::BLOCK_SIZE
/// [`MAX_CAPACITY`]: Self::MAX_CAPACITY
fn grow(&mut self, num_bytes: usize) -> io::Result<()> {
let min_size = self.block.len() + num_bytes;
let new_size = match min_size % Self::BLOCK_SIZE {
0 => min_size,
n => min_size + (Self::BLOCK_SIZE - n),
};
if new_size > Self::MAX_CAPACITY {
Err(io::Error::other("incoming data too large"))
} else {
self.block.resize(new_size, 0);
Ok(())
}
}
/// Return the block backing the buffer.
///
/// Next you *must* either return this block using [`return_block`] or call
/// [`reset_with_data`].
///
/// [`return_block`]: Self::return_block
/// [`reset_with_data`]: Self::reset_with_data
// TODO: Enforce this with typestate.
fn take_block(&mut self) -> BytesMut {
std::mem::replace(&mut self.block, BytesMut::zeroed(Self::BLOCK_SIZE))
}
/// Reset the buffer to be a new allocation with given data copied in.
///
/// This allows the previously returned block from `get_block` to be used in and owned
/// by the [ResponseData].
///
/// This does not do any bounds checking to see if the new buffer would exceed the
/// maximum size. It will however ensure that there is at least some free space at the
/// end of the buffer so that the next reading operation won't need to realloc right
/// away. This could be wasteful if the next action on the buffer is another decode
/// rather than a read, but we don't know.
fn reset_with_data(&mut self, data: &[u8]) {
let min_size = data.len();
let new_size = match min_size % Self::BLOCK_SIZE {
0 => min_size + Self::BLOCK_SIZE,
n => min_size + (Self::BLOCK_SIZE - n),
};
self.block = BytesMut::zeroed(new_size);
self.block[..data.len()].copy_from_slice(data);
self.offset = data.len();
}
/// Return the block which backs this buffer.
fn return_block(&mut self, block: BytesMut) {
self.block = block;
}
}
impl fmt::Debug for Buffer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Buffer")
.field("used", &self.used())
.field("capacity", &self.block.capacity())
.finish()
}
}
impl<R: Read + Write + Unpin> Stream for ImapStream<R> {
type Item = io::Result<ResponseData>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.read_closed {
return Poll::Ready(None);
}
let res = match ready!(self.as_mut().do_poll_next(cx)) {
None => None,
Some(Err(err)) => {
self.read_closed = true;
Some(Err(err))
}
Some(Ok(item)) => Some(Ok(item)),
};
Poll::Ready(res)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pin_project::pin_project;
use std::io::Write as _;
/// Wrapper for a stream that
/// fails once on a first read.
///
/// Writes are discarded.
#[pin_project]
struct FailingStream {
#[pin]
inner: &'static [u8],
has_failed: bool,
}
impl FailingStream {
fn new(buf: &'static [u8]) -> Self {
Self {
inner: buf,
has_failed: false,
}
}
}
#[cfg(feature = "runtime-tokio")]
impl Read for FailingStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<tokio::io::Result<()>> {
let this = self.project();
if !*this.has_failed {
*this.has_failed = true;
Poll::Ready(Err(std::io::Error::other("Failure")))
} else {
this.inner.poll_read(cx, buf)
}
}
}
#[cfg(feature = "runtime-async-std")]
impl Read for FailingStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<async_std::io::Result<usize>> {
let this = self.project();
if !*this.has_failed {
*this.has_failed = true;
Poll::Ready(Err(std::io::Error::other("Failure")))
} else {
this.inner.poll_read(cx, buf)
}
}
}
#[cfg(feature = "runtime-tokio")]
impl Write for FailingStream {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<tokio::io::Result<usize>> {
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<tokio::io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<tokio::io::Result<()>> {
Poll::Ready(Ok(()))
}
}
#[cfg(feature = "runtime-async-std")]
impl Write for FailingStream {
fn poll_write(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<async_std::io::Result<usize>> {
Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<async_std::io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_close(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<async_std::io::Result<()>> {
Poll::Ready(Ok(()))
}
}
/// Tests that stream returns `None` after
/// a single error of the underlying stream.
///
/// This is need to prevent accidental
/// reading from a network stream
/// after a temporary error such as a timeout
/// or returning an inifinite stream of errors.
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
#[cfg_attr(feature = "runtime-async-std", async_std::test)]
async fn test_imap_stream_error() {
use futures::StreamExt;
let mock_stream = FailingStream::new(b"* OK\r\n");
let mut imap_stream = ImapStream::new(mock_stream);
// First call is an error because underlying stream fails.
assert!(imap_stream.next().await.unwrap().is_err());
// IMAP stream should end even though underlying stream fails only once.
assert!(imap_stream.next().await.is_none());
}
#[test]
fn test_buffer_empty() {
let buf = Buffer::new();
assert_eq!(buf.used(), 0);
let mut buf = Buffer::new();
let slice: &[u8] = buf.free_as_mut_slice();
assert_eq!(slice.len(), Buffer::BLOCK_SIZE);
assert_eq!(slice.len(), buf.block.len());
}
#[test]
fn test_buffer_extend_use() {
let mut buf = Buffer::new();
buf.extend_used(3);
assert_eq!(buf.used(), 3);
let slice = buf.free_as_mut_slice();
assert_eq!(slice.len(), Buffer::BLOCK_SIZE - 3);
// Extend past the end of the buffer.
buf.extend_used(Buffer::BLOCK_SIZE);
assert_eq!(buf.used(), Buffer::BLOCK_SIZE);
assert_eq!(buf.offset, Buffer::BLOCK_SIZE);
assert_eq!(buf.block.len(), buf.offset);
let slice = buf.free_as_mut_slice();
assert_eq!(slice.len(), 0);
}
#[test]
fn test_buffer_write_read() {
let mut buf = Buffer::new();
let mut slice = buf.free_as_mut_slice();
slice.write_all(b"hello").unwrap();
buf.extend_used(b"hello".len());
let slice = &buf.block[..buf.used()];
assert_eq!(slice, b"hello");
assert_eq!(buf.free_as_mut_slice().len(), buf.block.len() - buf.offset);
}
#[test]
fn test_buffer_grow() {
let mut buf = Buffer::new();
assert_eq!(buf.block.len(), Buffer::BLOCK_SIZE);
buf.grow(1).unwrap();
assert_eq!(buf.block.len(), 2 * Buffer::BLOCK_SIZE);
buf.grow(Buffer::BLOCK_SIZE + 1).unwrap();
assert_eq!(buf.block.len(), 4 * Buffer::BLOCK_SIZE);
let ret = buf.grow(Buffer::MAX_CAPACITY);
assert!(ret.is_err());
}
#[test]
fn test_buffer_ensure_capacity() {
// Initial state: 1 byte capacity left, initial size.
let mut buf = Buffer::new();
buf.extend_used(Buffer::BLOCK_SIZE - 1);
assert_eq!(buf.free_as_mut_slice().len(), 1);
assert_eq!(buf.block.len(), Buffer::BLOCK_SIZE);
// Still has capacity, no size request.
buf.ensure_capacity(0).unwrap();
assert_eq!(buf.free_as_mut_slice().len(), 1);
assert_eq!(buf.block.len(), Buffer::BLOCK_SIZE);
// No more capacity, initial size.
buf.extend_used(1);
assert_eq!(buf.free_as_mut_slice().len(), 0);
assert_eq!(buf.block.len(), Buffer::BLOCK_SIZE);
// No capacity, no size request.
buf.ensure_capacity(0).unwrap();
assert_eq!(buf.free_as_mut_slice().len(), Buffer::BLOCK_SIZE);
assert_eq!(buf.block.len(), 2 * Buffer::BLOCK_SIZE);
// Some capacity, size request.
buf.extend_used(5);
assert_eq!(buf.offset, Buffer::BLOCK_SIZE + 5);
buf.ensure_capacity(3 * Buffer::BLOCK_SIZE - 6).unwrap();
assert_eq!(buf.free_as_mut_slice().len(), 2 * Buffer::BLOCK_SIZE - 5);
assert_eq!(buf.block.len(), 3 * Buffer::BLOCK_SIZE);
}
/// Regression test for a bug in ensure_capacity() caused
/// by a bug in byte-pool crate 0.2.2 dependency.
///
/// ensure_capacity() sometimes did not ensure that
/// at least one byte is available, which in turn
/// resulted in attempt to read into a buffer of zero size.
/// When poll_read() reads into a buffer of zero size,
/// it can only read zero bytes, which is indistinguishable
/// from EOF and resulted in an erroneous detection of EOF
/// when in fact the stream was not closed.
#[test]
fn test_ensure_capacity_loop() {
let mut buf = Buffer::new();
for i in 1..500 {
// Ask for `i` bytes.
buf.ensure_capacity(i).unwrap();
// Test that we can read at least 1 byte.
let free = buf.free_as_mut_slice();
let used = free.len();
assert!(used > 0);
// Use as much as allowed.
buf.extend_used(used);
// Test that we can read at least as much as requested.
let block = buf.take_block();
assert!(block.len() >= i);
buf.return_block(block);
}
}
#[test]
fn test_buffer_take_and_return_block() {
// This test identifies blocks by their size.
let mut buf = Buffer::new();
buf.grow(1).unwrap();
let block_size = buf.block.len();
let block = buf.take_block();
assert_eq!(block.len(), block_size);
assert_ne!(buf.block.len(), block_size);
buf.return_block(block);
assert_eq!(buf.block.len(), block_size);
}
#[test]
fn test_buffer_reset_with_data() {
// This test identifies blocks by their size.
let data: [u8; 2 * Buffer::BLOCK_SIZE] = [b'a'; 2 * Buffer::BLOCK_SIZE];
let mut buf = Buffer::new();
let block_size = buf.block.len();
assert_eq!(block_size, Buffer::BLOCK_SIZE);
buf.reset_with_data(&data);
assert_ne!(buf.block.len(), block_size);
assert_eq!(buf.block.len(), 3 * Buffer::BLOCK_SIZE);
assert!(!buf.free_as_mut_slice().is_empty());
let data: [u8; 0] = [];
let mut buf = Buffer::new();
buf.reset_with_data(&data);
assert_eq!(buf.block.len(), Buffer::BLOCK_SIZE);
}
#[test]
fn test_buffer_debug() {
assert_eq!(
format!("{:?}", Buffer::new()),
format!(r#"Buffer {{ used: 0, capacity: {} }}"#, Buffer::BLOCK_SIZE)
);
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/authenticator.rs | src/authenticator.rs | /// This trait allows for pluggable authentication schemes. It is used by [`Client::authenticate`] to
/// [authenticate using SASL](https://tools.ietf.org/html/rfc3501#section-6.2.2).
///
/// [`Client::authenticate`]: crate::Client::authenticate
pub trait Authenticator {
/// The type of the response to the challenge. This will usually be a `Vec<u8>` or `String`.
type Response: AsRef<[u8]>;
/// Each base64-decoded server challenge is passed to `process`.
/// The returned byte-string is base64-encoded and then sent back to the server.
fn process(&mut self, challenge: &[u8]) -> Self::Response;
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/extensions/idle.rs | src/extensions/idle.rs | //! Adds support for the IMAP IDLE command specificed in [RFC2177](https://tools.ietf.org/html/rfc2177).
use std::fmt;
use std::pin::Pin;
use std::time::Duration;
#[cfg(feature = "runtime-async-std")]
use async_std::{
future::timeout,
io::{Read, Write},
};
use futures::prelude::*;
use futures::task::{Context, Poll};
use imap_proto::{RequestId, Response, Status};
use stop_token::prelude::*;
#[cfg(feature = "runtime-tokio")]
use tokio::{
io::{AsyncRead as Read, AsyncWrite as Write},
time::timeout,
};
use crate::client::Session;
use crate::error::Result;
use crate::parse::handle_unilateral;
use crate::types::ResponseData;
/// `Handle` allows a client to block waiting for changes to the remote mailbox.
///
/// The handle blocks using the [`IDLE` command](https://tools.ietf.org/html/rfc2177#section-3)
/// specificed in [RFC 2177](https://tools.ietf.org/html/rfc2177) until the underlying server state
/// changes in some way. While idling does inform the client what changes happened on the server,
/// this implementation will currently just block until _anything_ changes, and then notify the
///
/// Note that the server MAY consider a client inactive if it has an IDLE command running, and if
/// such a server has an inactivity timeout it MAY log the client off implicitly at the end of its
/// timeout period. Because of that, clients using IDLE are advised to terminate the IDLE and
/// re-issue it at least every 29 minutes to avoid being logged off. [`Handle::wait`]
/// does this. This still allows a client to receive immediate mailbox updates even though it need
/// only "poll" at half hour intervals.
///
/// As long as a [`Handle`] is active, the mailbox cannot be otherwise accessed.
#[derive(Debug)]
pub struct Handle<T: Read + Write + Unpin + fmt::Debug> {
session: Session<T>,
id: Option<RequestId>,
}
impl<T: Read + Write + Unpin + fmt::Debug> Unpin for Handle<T> {}
impl<T: Read + Write + Unpin + fmt::Debug + Send> Stream for Handle<T> {
type Item = std::io::Result<ResponseData>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.as_mut().session().get_stream().poll_next(cx)
}
}
/// A stream of server responses after sending `IDLE`.
#[derive(Debug)]
#[must_use = "futures do nothing unless polled"]
pub struct IdleStream<'a, St> {
stream: &'a mut St,
}
impl<St: Unpin> Unpin for IdleStream<'_, St> {}
impl<'a, St: Stream + Unpin> IdleStream<'a, St> {
unsafe_pinned!(stream: &'a mut St);
pub(crate) fn new(stream: &'a mut St) -> Self {
IdleStream { stream }
}
}
impl<St: futures::stream::FusedStream + Unpin> futures::stream::FusedStream for IdleStream<'_, St> {
fn is_terminated(&self) -> bool {
self.stream.is_terminated()
}
}
impl<St: Stream + Unpin> Stream for IdleStream<'_, St> {
type Item = St::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.stream().poll_next(cx)
}
}
/// Possible responses that happen on an open idle connection.
#[derive(Debug, PartialEq, Eq)]
pub enum IdleResponse {
/// The manual interrupt was used to interrupt the idle connection..
ManualInterrupt,
/// The idle connection timed out, because of the user set timeout.
Timeout,
/// The server has indicated that some new action has happened.
NewData(ResponseData),
}
// Make it possible to access the inner connection and modify its settings, such as read/write
// timeouts.
impl<T: Read + Write + Unpin + fmt::Debug> AsMut<T> for Handle<T> {
fn as_mut(&mut self) -> &mut T {
self.session.conn.stream.as_mut()
}
}
impl<T: Read + Write + Unpin + fmt::Debug + Send> Handle<T> {
unsafe_pinned!(session: Session<T>);
pub(crate) fn new(session: Session<T>) -> Handle<T> {
Handle { session, id: None }
}
/// Start listening to the server side responses.
/// Must be called after [`Handle::init`].
pub fn wait(
&mut self,
) -> (
impl Future<Output = Result<IdleResponse>> + '_,
stop_token::StopSource,
) {
self.wait_with_timeout(Duration::from_secs(29 * 60))
}
/// Start listening to the server side responses.
///
/// Stops after the passed in `timeout` without any response from the server.
/// Timeout is reset by any response, including `* OK Still here` keepalives.
///
/// Must be called after [Handle::init].
pub fn wait_with_timeout(
&mut self,
dur: Duration,
) -> (
impl Future<Output = Result<IdleResponse>> + '_,
stop_token::StopSource,
) {
assert!(
self.id.is_some(),
"Cannot listen to response without starting IDLE"
);
let sender = self.session.unsolicited_responses_tx.clone();
let interrupt = stop_token::StopSource::new();
let raw_stream = IdleStream::new(self);
let mut interruptible_stream = raw_stream.timeout_at(interrupt.token());
let fut = async move {
loop {
let Ok(res) = timeout(dur, interruptible_stream.next()).await else {
return Ok(IdleResponse::Timeout);
};
let Some(Ok(resp)) = res else {
return Ok(IdleResponse::ManualInterrupt);
};
let resp = resp?;
match resp.parsed() {
Response::Data {
status: Status::Ok, ..
} => {
// all good continue
}
Response::Continue { .. } => {
// continuation, wait for it
}
Response::Done { .. } => {
handle_unilateral(resp, sender.clone());
}
_ => return Ok(IdleResponse::NewData(resp)),
}
}
};
(fut, interrupt)
}
/// Initialise the idle connection by sending the `IDLE` command to the server.
pub async fn init(&mut self) -> Result<()> {
let id = self.session.run_command("IDLE").await?;
self.id = Some(id);
while let Some(res) = self.session.stream.try_next().await? {
match res.parsed() {
Response::Continue { .. } => {
return Ok(());
}
Response::Done {
tag,
status,
information,
..
} => {
if tag == self.id.as_ref().unwrap() {
if let Status::Bad = status {
return Err(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
information.as_ref().unwrap().to_string(),
)
.into());
}
}
handle_unilateral(res, self.session.unsolicited_responses_tx.clone());
}
_ => {
handle_unilateral(res, self.session.unsolicited_responses_tx.clone());
}
}
}
Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "").into())
}
/// Signal that we want to exit the idle connection, by sending the `DONE`
/// command to the server.
pub async fn done(mut self) -> Result<Session<T>> {
assert!(
self.id.is_some(),
"Cannot call DONE on a non initialized idle connection"
);
self.session.run_command_untagged("DONE").await?;
let sender = self.session.unsolicited_responses_tx.clone();
self.session
.check_done_ok(&self.id.expect("invalid setup"), Some(sender))
.await?;
Ok(self.session)
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/extensions/compress.rs | src/extensions/compress.rs | //! IMAP COMPRESS extension specified in [RFC4978](https://www.rfc-editor.org/rfc/rfc4978.html).
use std::fmt;
use std::pin::Pin;
use std::task::{Context, Poll};
use pin_project::pin_project;
use crate::client::Session;
use crate::error::Result;
use crate::imap_stream::ImapStream;
use crate::types::IdGenerator;
use crate::Connection;
#[cfg(feature = "runtime-async-std")]
use async_std::io::{IoSlice, IoSliceMut, Read, Write};
#[cfg(feature = "runtime-async-std")]
use futures::io::BufReader;
#[cfg(feature = "runtime-tokio")]
use tokio::io::{AsyncRead as Read, AsyncWrite as Write, BufReader, ReadBuf};
#[cfg(feature = "runtime-tokio")]
use async_compression::tokio::bufread::DeflateDecoder;
#[cfg(feature = "runtime-tokio")]
use async_compression::tokio::write::DeflateEncoder;
#[cfg(feature = "runtime-async-std")]
use async_compression::futures::bufread::DeflateDecoder;
#[cfg(feature = "runtime-async-std")]
use async_compression::futures::write::DeflateEncoder;
/// Network stream compressed with DEFLATE.
#[derive(Debug)]
#[pin_project]
pub struct DeflateStream<T: Read + Write + Unpin + fmt::Debug> {
#[pin]
inner: DeflateDecoder<BufReader<DeflateEncoder<T>>>,
}
impl<T: Read + Write + Unpin + fmt::Debug> DeflateStream<T> {
pub(crate) fn new(stream: T) -> Self {
let stream = DeflateEncoder::new(stream);
let stream = BufReader::new(stream);
let stream = DeflateDecoder::new(stream);
Self { inner: stream }
}
/// Gets a reference to the underlying stream.
pub fn get_ref(&self) -> &T {
self.inner.get_ref().get_ref().get_ref()
}
/// Gets a mutable reference to the underlying stream.
pub fn get_mut(&mut self) -> &mut T {
self.inner.get_mut().get_mut().get_mut()
}
/// Consumes `DeflateStream` and returns underlying stream.
pub fn into_inner(self) -> T {
self.inner.into_inner().into_inner().into_inner()
}
}
#[cfg(feature = "runtime-tokio")]
impl<T: Read + Write + Unpin + fmt::Debug> Read for DeflateStream<T> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
self.project().inner.poll_read(cx, buf)
}
}
#[cfg(feature = "runtime-async-std")]
impl<T: Read + Write + Unpin + fmt::Debug> Read for DeflateStream<T> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<async_std::io::Result<usize>> {
self.project().inner.poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<async_std::io::Result<usize>> {
self.project().inner.poll_read_vectored(cx, bufs)
}
}
#[cfg(feature = "runtime-tokio")]
impl<T: Read + Write + Unpin + fmt::Debug> Write for DeflateStream<T> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
self.project().inner.get_pin_mut().poll_write(cx, buf)
}
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_shutdown(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<std::io::Result<()>> {
self.project().inner.poll_shutdown(cx)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[std::io::IoSlice<'_>],
) -> Poll<std::io::Result<usize>> {
self.project().inner.poll_write_vectored(cx, bufs)
}
fn is_write_vectored(&self) -> bool {
self.inner.is_write_vectored()
}
}
#[cfg(feature = "runtime-async-std")]
impl<T: Read + Write + Unpin + fmt::Debug> Write for DeflateStream<T> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> Poll<async_std::io::Result<usize>> {
self.project().inner.as_mut().poll_write(cx, buf)
}
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<async_std::io::Result<()>> {
self.project().inner.poll_flush(cx)
}
fn poll_close(
self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<async_std::io::Result<()>> {
self.project().inner.poll_close(cx)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<async_std::io::Result<usize>> {
self.project().inner.poll_write_vectored(cx, bufs)
}
}
impl<T: Read + Write + Unpin + fmt::Debug + Send> Session<T> {
/// Runs `COMPRESS DEFLATE` command.
pub async fn compress<F, S>(self, f: F) -> Result<Session<S>>
where
S: Read + Write + Unpin + fmt::Debug,
F: FnOnce(DeflateStream<T>) -> S,
{
let Self {
mut conn,
unsolicited_responses_tx,
unsolicited_responses,
} = self;
conn.run_command_and_check_ok("COMPRESS DEFLATE", Some(unsolicited_responses_tx.clone()))
.await?;
let stream = conn.into_inner();
let deflate_stream = DeflateStream::new(stream);
let stream = ImapStream::new(f(deflate_stream));
let conn = Connection {
stream,
request_ids: IdGenerator::new(),
};
let session = Session {
conn,
unsolicited_responses_tx,
unsolicited_responses,
};
Ok(session)
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/extensions/id.rs | src/extensions/id.rs | //! IMAP ID extension specified in [RFC2971](https://datatracker.ietf.org/doc/html/rfc2971)
use async_channel as channel;
use futures::io;
use futures::prelude::*;
use imap_proto::{self, RequestId, Response};
use std::collections::HashMap;
use crate::types::ResponseData;
use crate::types::*;
use crate::{
error::Result,
parse::{filter, handle_unilateral},
};
fn escape(s: &str) -> String {
s.replace('\\', r"\\").replace('\"', "\\\"")
}
/// Formats list of key-value pairs for ID command.
///
/// Returned list is not wrapped in parenthesis, the caller should do it.
pub(crate) fn format_identification<'a, 'b>(
id: impl IntoIterator<Item = (&'a str, Option<&'b str>)>,
) -> String {
id.into_iter()
.map(|(k, v)| {
format!(
"\"{}\" {}",
escape(k),
v.map_or("NIL".to_string(), |v| format!("\"{}\"", escape(v)))
)
})
.collect::<Vec<String>>()
.join(" ")
}
pub(crate) async fn parse_id<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Option<HashMap<String, String>>> {
let mut id = None;
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
Response::Id(res) => {
id = res.as_ref().map(|m| {
m.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect()
})
}
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok(id)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_format_identification() {
assert_eq!(
format_identification([("name", Some("MyClient"))]),
r#""name" "MyClient""#
);
assert_eq!(
format_identification([("name", Some(r#""MyClient"\"#))]),
r#""name" "\"MyClient\"\\""#
);
assert_eq!(
format_identification([("name", Some("MyClient")), ("version", Some("2.0"))]),
r#""name" "MyClient" "version" "2.0""#
);
assert_eq!(
format_identification([("name", None), ("version", Some("2.0"))]),
r#""name" NIL "version" "2.0""#
);
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/extensions/mod.rs | src/extensions/mod.rs | //! Implementations of various IMAP extensions.
#[cfg(feature = "compress")]
pub mod compress;
pub mod idle;
pub mod quota;
pub mod id;
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/extensions/quota.rs | src/extensions/quota.rs | //! Adds support for the GETQUOTA and GETQUOTAROOT commands specificed in [RFC2087](https://tools.ietf.org/html/rfc2087).
use async_channel as channel;
use futures::io;
use futures::prelude::*;
use imap_proto::{self, RequestId, Response};
use crate::types::*;
use crate::{
error::Result,
parse::{filter, handle_unilateral},
};
use crate::{
error::{Error, ParseError},
types::{Quota, QuotaRoot, ResponseData},
};
pub(crate) async fn parse_get_quota<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<Quota> {
let mut quota = None;
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
Response::Quota(q) => quota = Some(q.clone().into()),
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
match quota {
Some(q) => Ok(q),
None => Err(Error::Parse(ParseError::ExpectedResponseNotFound(
"Quota, no quota response found".to_string(),
))),
}
}
pub(crate) async fn parse_get_quota_root<T: Stream<Item = io::Result<ResponseData>> + Unpin>(
stream: &mut T,
unsolicited: channel::Sender<UnsolicitedResponse>,
command_tag: RequestId,
) -> Result<(Vec<QuotaRoot>, Vec<Quota>)> {
let mut roots: Vec<QuotaRoot> = Vec::new();
let mut quotas: Vec<Quota> = Vec::new();
while let Some(resp) = stream
.take_while(|res| filter(res, &command_tag))
.try_next()
.await?
{
match resp.parsed() {
Response::QuotaRoot(qr) => {
roots.push(qr.clone().into());
}
Response::Quota(q) => {
quotas.push(q.clone().into());
}
_ => {
handle_unilateral(resp, unsolicited.clone());
}
}
}
Ok((roots, quotas))
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/mailbox.rs | src/types/mailbox.rs | use super::{Flag, Uid};
use std::fmt;
/// Meta-information about an IMAP mailbox, as returned by
/// [`SELECT`](https://tools.ietf.org/html/rfc3501#section-6.3.1) and friends.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Default)]
pub struct Mailbox {
/// Defined flags in the mailbox. See the description of the [FLAGS
/// response](https://tools.ietf.org/html/rfc3501#section-7.2.6) for more detail.
pub flags: Vec<Flag<'static>>,
/// The number of messages in the mailbox. See the description of the [EXISTS
/// response](https://tools.ietf.org/html/rfc3501#section-7.3.1) for more detail.
pub exists: u32,
/// The number of messages with the \Recent flag set. See the description of the [RECENT
/// response](https://tools.ietf.org/html/rfc3501#section-7.3.2) for more detail.
pub recent: u32,
/// The message sequence number of the first unseen message in the mailbox. If this is
/// missing, the client can not make any assumptions about the first unseen message in the
/// mailbox, and needs to issue a `SEARCH` command if it wants to find it.
pub unseen: Option<u32>,
/// A list of message flags that the client can change permanently. If this is missing, the
/// client should assume that all flags can be changed permanently. If the client attempts to
/// STORE a flag that is not in this list list, the server will either ignore the change or
/// store the state change for the remainder of the current session only.
pub permanent_flags: Vec<Flag<'static>>,
/// The next unique identifier value. If this is missing, the client can not make any
/// assumptions about the next unique identifier value.
pub uid_next: Option<Uid>,
/// The unique identifier validity value. See [`Uid`] for more details. If this is missing,
/// the server does not support unique identifiers.
pub uid_validity: Option<u32>,
/// Highest mailbox mod-sequence as defined in [RFC-7162](https://tools.ietf.org/html/rfc7162).
pub highest_modseq: Option<u64>,
}
impl fmt::Display for Mailbox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"flags: {:?}, exists: {}, recent: {}, unseen: {:?}, permanent_flags: {:?},\
uid_next: {:?}, uid_validity: {:?}",
self.flags,
self.exists,
self.recent,
self.unseen,
self.permanent_flags,
self.uid_next,
self.uid_validity
)
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/fetch.rs | src/types/fetch.rs | use std::borrow::Cow;
use chrono::{DateTime, FixedOffset};
use imap_proto::types::{
AttributeValue, BodyStructure, Envelope, MessageSection, Response, SectionPath,
};
use super::{Flag, Seq, Uid};
use crate::types::ResponseData;
/// Format of Date and Time as defined RFC3501.
/// See `date-time` element in [Formal Syntax](https://tools.ietf.org/html/rfc3501#section-9)
/// chapter of this RFC.
const DATE_TIME_FORMAT: &str = "%d-%b-%Y %H:%M:%S %z";
/// An IMAP [`FETCH` response](https://tools.ietf.org/html/rfc3501#section-7.4.2) that contains
/// data about a particular message.
///
/// This response occurs as the result of a `FETCH` or `STORE`
/// command, as well as by unilateral server decision (e.g., flag updates).
#[derive(Debug)]
pub struct Fetch {
response: ResponseData,
/// The ordinal number of this message in its containing mailbox.
pub message: Seq,
/// A number expressing the unique identifier of the message.
/// Only present if `UID` was specified in the query argument to `FETCH` and the server
/// supports UIDs.
pub uid: Option<Uid>,
/// A number expressing the [RFC-2822](https://tools.ietf.org/html/rfc2822) size of the message.
/// Only present if `RFC822.SIZE` was specified in the query argument to `FETCH`.
pub size: Option<u32>,
/// A number expressing the [RFC-7162](https://tools.ietf.org/html/rfc7162) mod-sequence
/// of the message.
pub modseq: Option<u64>,
}
impl Fetch {
pub(crate) fn new(response: ResponseData) -> Self {
let (message, uid, size, modseq) =
if let Response::Fetch(message, attrs) = response.parsed() {
let mut uid = None;
let mut size = None;
let mut modseq = None;
for attr in attrs {
match attr {
AttributeValue::Uid(id) => uid = Some(*id),
AttributeValue::Rfc822Size(sz) => size = Some(*sz),
AttributeValue::ModSeq(ms) => modseq = Some(*ms),
_ => {}
}
}
(*message, uid, size, modseq)
} else {
unreachable!()
};
Fetch {
response,
message,
uid,
size,
modseq,
}
}
/// A list of flags that are set for this message.
pub fn flags(&self) -> impl Iterator<Item = Flag<'_>> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|attr| match attr {
AttributeValue::Flags(raw_flags) => {
Some(raw_flags.iter().map(|s| Flag::from(s.as_ref())))
}
_ => None,
})
.flatten()
} else {
unreachable!()
}
}
/// The bytes that make up the header of this message, if `BODY[HEADER]`, `BODY.PEEK[HEADER]`,
/// or `RFC822.HEADER` was included in the `query` argument to `FETCH`.
pub fn header(&self) -> Option<&[u8]> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::BodySection {
section: Some(SectionPath::Full(MessageSection::Header)),
data: Some(hdr),
..
}
| AttributeValue::Rfc822Header(Some(hdr)) => Some(hdr.as_ref()),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// The bytes that make up this message, included if `BODY[]` or `RFC822` was included in the
/// `query` argument to `FETCH`. The bytes SHOULD be interpreted by the client according to the
/// content transfer encoding, body type, and subtype.
pub fn body(&self) -> Option<&[u8]> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::BodySection {
section: None,
data: Some(body),
..
}
| AttributeValue::Rfc822(Some(body)) => Some(body.as_ref()),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// The bytes that make up the text of this message, included if `BODY[TEXT]`, `RFC822.TEXT`,
/// or `BODY.PEEK[TEXT]` was included in the `query` argument to `FETCH`. The bytes SHOULD be
/// interpreted by the client according to the content transfer encoding, body type, and
/// subtype.
pub fn text(&self) -> Option<&[u8]> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::BodySection {
section: Some(SectionPath::Full(MessageSection::Text)),
data: Some(body),
..
}
| AttributeValue::Rfc822Text(Some(body)) => Some(body.as_ref()),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// The envelope of this message, if `ENVELOPE` was included in the `query` argument to
/// `FETCH`. This is computed by the server by parsing the
/// [RFC-2822](https://tools.ietf.org/html/rfc2822) header into the component parts, defaulting
/// various fields as necessary.
///
/// The full description of the format of the envelope is given in [RFC 3501 section
/// 7.4.2](https://tools.ietf.org/html/rfc3501#section-7.4.2).
pub fn envelope(&self) -> Option<&Envelope<'_>> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::Envelope(env) => Some(&**env),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// Extract the bytes that makes up the given `BOD[<section>]` of a `FETCH` response.
///
/// See [section 7.4.2 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-7.4.2) for
/// details.
pub fn section(&self, path: &SectionPath) -> Option<&[u8]> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::BodySection {
section: Some(sp),
data: Some(data),
..
} if sp == path => Some(data.as_ref()),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// Extract the `INTERNALDATE` of a `FETCH` response
///
/// See [section 2.3.3 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-2.3.3) for
/// details.
pub fn internal_date(&self) -> Option<DateTime<FixedOffset>> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::InternalDate(date_time) => Some(date_time.as_ref()),
_ => None,
})
.next()
.and_then(|date_time| DateTime::parse_from_str(date_time, DATE_TIME_FORMAT).ok())
} else {
unreachable!()
}
}
/// Extract the `BODYSTRUCTURE` of a `FETCH` response
///
/// See [section 2.3.6 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-2.3.6) for
/// details.
pub fn bodystructure(&self) -> Option<&BodyStructure<'_>> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::BodyStructure(bs) => Some(bs),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// Extract the `X-GM-LABELS` of a `FETCH` response
///
/// See [Access to Gmail labels: X-GM-LABELS](https://developers.google.com/gmail/imap/imap-extensions#access_to_labels_x-gm-labels)
/// for details.
pub fn gmail_labels(&self) -> Option<&Vec<Cow<'_, str>>> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::GmailLabels(gl) => Some(gl),
_ => None,
})
.next()
} else {
unreachable!()
}
}
/// Extract the `X-GM-MSGID` of a `FETCH` response
///
/// See [Access to the Gmail unique message ID: X-GM-MSGID](https://developers.google.com/workspace/gmail/imap/imap-extensions#access_to_the_unique_message_id_x-gm-msgid)
/// for details.
pub fn gmail_msg_id(&self) -> Option<&u64> {
if let Response::Fetch(_, attrs) = self.response.parsed() {
attrs
.iter()
.filter_map(|av| match av {
AttributeValue::GmailMsgId(id) => Some(id),
_ => None,
})
.next()
} else {
unreachable!()
}
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/mod.rs | src/types/mod.rs | //! This module contains types used throughout the IMAP protocol.
use std::borrow::Cow;
/// From section [2.3.1.1 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-2.3.1.1).
///
/// A 32-bit value assigned to each message, which when used with the unique identifier validity
/// value (see below) forms a 64-bit value that will not refer to any other message in the mailbox
/// or any subsequent mailbox with the same name forever. Unique identifiers are assigned in a
/// strictly ascending fashion in the mailbox; as each message is added to the mailbox it is
/// assigned a higher UID than the message(s) which were added previously. Unlike message sequence
/// numbers, unique identifiers are not necessarily contiguous.
///
/// The unique identifier of a message will not change during the session, and will generally not
/// change between sessions. Any change of unique identifiers between sessions will be detectable
/// using the `UIDVALIDITY` mechanism discussed below. Persistent unique identifiers are required
/// for a client to resynchronize its state from a previous session with the server (e.g.,
/// disconnected or offline access clients); this is discussed further in
/// [`IMAP-DISC`](https://tools.ietf.org/html/rfc3501#ref-IMAP-DISC).
///
/// Associated with every mailbox are two values which aid in unique identifier handling: the next
/// unique identifier value and the unique identifier validity value.
///
/// The next unique identifier value is the predicted value that will be assigned to a new message
/// in the mailbox. Unless the unique identifier validity also changes (see below), the next
/// unique identifier value will have the following two characteristics. First, the next unique
/// identifier value will not change unless new messages are added to the mailbox; and second, the
/// next unique identifier value will change whenever new messages are added to the mailbox, even
/// if those new messages are subsequently expunged.
///
/// > Note: The next unique identifier value is intended to provide a means for a client to
/// > determine whether any messages have been delivered to the mailbox since the previous time it
/// > checked this value. It is not intended to provide any guarantee that any message will have
/// > this unique identifier. A client can only assume, at the time that it obtains the next
/// > unique identifier value, that messages arriving after that time will have a UID greater than
/// > or equal to that value.
///
/// The unique identifier validity value is sent in a `UIDVALIDITY` response code in an `OK`
/// untagged response at mailbox selection time. If unique identifiers from an earlier session fail
/// to persist in this session, the unique identifier validity value will be greater than the one
/// used in the earlier session.
///
/// > Note: Ideally, unique identifiers will persist at all
/// > times. Although this specification recognizes that failure
/// > to persist can be unavoidable in certain server
/// > environments, it STRONGLY ENCOURAGES message store
/// > implementation techniques that avoid this problem. For
/// > example:
/// >
/// > 1. Unique identifiers are strictly ascending in the
/// > mailbox at all times. If the physical message store is
/// > re-ordered by a non-IMAP agent, this requires that the
/// > unique identifiers in the mailbox be regenerated, since
/// > the former unique identifiers are no longer strictly
/// > ascending as a result of the re-ordering.
/// > 2. If the message store has no mechanism to store unique
/// > identifiers, it must regenerate unique identifiers at
/// > each session, and each session must have a unique
/// > `UIDVALIDITY` value.
/// > 3. If the mailbox is deleted and a new mailbox with the
/// > same name is created at a later date, the server must
/// > either keep track of unique identifiers from the
/// > previous instance of the mailbox, or it must assign a
/// > new `UIDVALIDITY` value to the new instance of the
/// > mailbox. A good `UIDVALIDITY` value to use in this case
/// > is a 32-bit representation of the creation date/time of
/// > the mailbox. It is alright to use a constant such as
/// > 1, but only if it guaranteed that unique identifiers
/// > will never be reused, even in the case of a mailbox
/// > being deleted (or renamed) and a new mailbox by the
/// > same name created at some future time.
/// > 4. The combination of mailbox name, `UIDVALIDITY`, and `UID`
/// > must refer to a single immutable message on that server
/// > forever. In particular, the internal date, [RFC 2822](https://tools.ietf.org/html/rfc2822)
/// > size, envelope, body structure, and message texts
/// > (RFC822, RFC822.HEADER, RFC822.TEXT, and all BODY[...]
/// > fetch data items) must never change. This does not
/// > include message numbers, nor does it include attributes
/// > that can be set by a `STORE` command (e.g., `FLAGS`).
pub type Uid = u32;
/// From section [2.3.1.2 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-2.3.1.2).
///
/// A relative position from 1 to the number of messages in the mailbox.
/// This position is ordered by ascending unique identifier. As
/// each new message is added, it is assigned a message sequence number
/// that is 1 higher than the number of messages in the mailbox before
/// that new message was added.
///
/// Message sequence numbers can be reassigned during the session. For
/// example, when a message is permanently removed (expunged) from the
/// mailbox, the message sequence number for all subsequent messages is
/// decremented. The number of messages in the mailbox is also
/// decremented. Similarly, a new message can be assigned a message
/// sequence number that was once held by some other message prior to an
/// expunge.
///
/// In addition to accessing messages by relative position in the
/// mailbox, message sequence numbers can be used in mathematical
/// calculations. For example, if an untagged "11 EXISTS" is received,
/// and previously an untagged "8 EXISTS" was received, three new
/// messages have arrived with message sequence numbers of 9, 10, and 11.
/// Another example, if message 287 in a 523 message mailbox has UID
/// 12345, there are exactly 286 messages which have lesser UIDs and 236
/// messages which have greater UIDs.
pub type Seq = u32;
/// Message flags.
///
/// With the exception of [`Flag::Custom`], these flags are system flags that are pre-defined in
/// [RFC 3501 section 2.3.2](https://tools.ietf.org/html/rfc3501#section-2.3.2). All system flags
/// begin with `\` in the IMAP protocol. Certain system flags (`\Deleted` and `\Seen`) have
/// special semantics described elsewhere.
///
/// A flag can be permanent or session-only on a per-flag basis. Permanent flags are those which
/// the client can add or remove from the message flags permanently; that is, concurrent and
/// subsequent sessions will see any change in permanent flags. Changes to session flags are valid
/// only in that session.
///
/// > Note: The `\Recent` system flag is a special case of a session flag. `\Recent` can not be
/// > used as an argument in a `STORE` or `APPEND` command, and thus can not be changed at all.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum Flag<'a> {
/// Message has been read
Seen,
/// Message has been answered
Answered,
/// Message is "flagged" for urgent/special attention
Flagged,
/// Message is "deleted" for removal by later EXPUNGE
Deleted,
/// Message has not completed composition (marked as a draft).
Draft,
/// Message is "recently" arrived in this mailbox. This session is the first session to have
/// been notified about this message; if the session is read-write, subsequent sessions will
/// not see `\Recent` set for this message. This flag can not be altered by the client.
///
/// If it is not possible to determine whether or not this session is the first session to be
/// notified about a message, then that message will generally be considered recent.
///
/// If multiple connections have the same mailbox selected simultaneously, it is undefined
/// which of these connections will see newly-arrived messages with `\Recent` set and which
/// will see it without `\Recent` set.
Recent,
/// The [`Mailbox::permanent_flags`] can include this special flag (`\*`), which indicates that
/// it is possible to create new keywords by attempting to store those flags in the mailbox.
MayCreate,
/// A non-standard user- or server-defined flag.
Custom(Cow<'a, str>),
}
impl Flag<'static> {
fn system(s: &str) -> Option<Self> {
match s {
"\\Seen" => Some(Flag::Seen),
"\\Answered" => Some(Flag::Answered),
"\\Flagged" => Some(Flag::Flagged),
"\\Deleted" => Some(Flag::Deleted),
"\\Draft" => Some(Flag::Draft),
"\\Recent" => Some(Flag::Recent),
"\\*" => Some(Flag::MayCreate),
_ => None,
}
}
}
impl From<String> for Flag<'_> {
fn from(s: String) -> Self {
if let Some(f) = Flag::system(&s) {
f
} else {
Flag::Custom(Cow::Owned(s))
}
}
}
impl<'a> From<&'a str> for Flag<'a> {
fn from(s: &'a str) -> Self {
if let Some(f) = Flag::system(s) {
f
} else {
Flag::Custom(Cow::Borrowed(s))
}
}
}
mod mailbox;
pub use self::mailbox::Mailbox;
mod fetch;
pub use self::fetch::Fetch;
mod name;
pub use self::name::{Name, NameAttribute};
mod capabilities;
pub use self::capabilities::{Capabilities, Capability};
/// re-exported from imap_proto;
pub use imap_proto::StatusAttribute;
mod id_generator;
pub(crate) use self::id_generator::IdGenerator;
mod response_data;
pub(crate) use self::response_data::ResponseData;
mod request;
pub(crate) use self::request::Request;
mod quota;
pub use self::quota::*;
/// Responses that the server sends that are not related to the current command.
///
/// [RFC 3501](https://tools.ietf.org/html/rfc3501#section-7) states that clients need to be able
/// to accept any response at any time. These are the ones we've encountered in the wild.
///
/// Note that `Recent`, `Exists` and `Expunge` responses refer to the currently `SELECT`ed folder,
/// so the user must take care when interpreting these.
#[derive(Debug, PartialEq, Eq)]
pub enum UnsolicitedResponse {
/// An unsolicited [`STATUS response`](https://tools.ietf.org/html/rfc3501#section-7.2.4).
Status {
/// The mailbox that this status response is for.
mailbox: String,
/// The attributes of this mailbox.
attributes: Vec<StatusAttribute>,
},
/// An unsolicited [`RECENT` response](https://tools.ietf.org/html/rfc3501#section-7.3.2)
/// indicating the number of messages with the `\Recent` flag set. This response occurs if the
/// size of the mailbox changes (e.g., new messages arrive).
///
/// > Note: It is not guaranteed that the message sequence
/// > numbers of recent messages will be a contiguous range of
/// > the highest n messages in the mailbox (where n is the
/// > value reported by the `RECENT` response). Examples of
/// > situations in which this is not the case are: multiple
/// > clients having the same mailbox open (the first session
/// > to be notified will see it as recent, others will
/// > probably see it as non-recent), and when the mailbox is
/// > re-ordered by a non-IMAP agent.
/// >
/// > The only reliable way to identify recent messages is to
/// > look at message flags to see which have the `\Recent` flag
/// > set, or to do a `SEARCH RECENT`.
Recent(u32),
/// An unsolicited [`EXISTS` response](https://tools.ietf.org/html/rfc3501#section-7.3.1) that
/// reports the number of messages in the mailbox. This response occurs if the size of the
/// mailbox changes (e.g., new messages arrive).
Exists(u32),
/// An unsolicited [`EXPUNGE` response](https://tools.ietf.org/html/rfc3501#section-7.4.1) that
/// reports that the specified message sequence number has been permanently removed from the
/// mailbox. The message sequence number for each successive message in the mailbox is
/// immediately decremented by 1, and this decrement is reflected in message sequence numbers
/// in subsequent responses (including other untagged `EXPUNGE` responses).
///
/// The EXPUNGE response also decrements the number of messages in the mailbox; it is not
/// necessary to send an `EXISTS` response with the new value.
///
/// As a result of the immediate decrement rule, message sequence numbers that appear in a set
/// of successive `EXPUNGE` responses depend upon whether the messages are removed starting
/// from lower numbers to higher numbers, or from higher numbers to lower numbers. For
/// example, if the last 5 messages in a 9-message mailbox are expunged, a "lower to higher"
/// server will send five untagged `EXPUNGE` responses for message sequence number 5, whereas a
/// "higher to lower server" will send successive untagged `EXPUNGE` responses for message
/// sequence numbers 9, 8, 7, 6, and 5.
// TODO: the spec doesn't seem to say anything about when these may be received as unsolicited?
Expunge(u32),
/// Any other kind of unsolicted response.
Other(ResponseData),
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/quota.rs | src/types/quota.rs | use imap_proto::types::Quota as QuotaRef;
use imap_proto::types::QuotaResource as QuotaResourceRef;
use imap_proto::types::QuotaResourceName as QuotaResourceNameRef;
use imap_proto::types::QuotaRoot as QuotaRootRef;
/// <https://tools.ietf.org/html/rfc2087#section-3>
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub enum QuotaResourceName {
/// Sum of messages' RFC822.SIZE, in units of 1024 octets
Storage,
/// Number of messages
Message,
/// A different/custom resource
Atom(String),
}
impl From<QuotaResourceNameRef<'_>> for QuotaResourceName {
fn from(name: QuotaResourceNameRef<'_>) -> Self {
match name {
QuotaResourceNameRef::Message => QuotaResourceName::Message,
QuotaResourceNameRef::Storage => QuotaResourceName::Storage,
QuotaResourceNameRef::Atom(v) => QuotaResourceName::Atom(v.to_string()),
}
}
}
/// 5.1. QUOTA Response (<https://tools.ietf.org/html/rfc2087#section-5.1>)
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct QuotaResource {
/// name of the resource
pub name: QuotaResourceName,
/// current usage of the resource
pub usage: u64,
/// resource limit
pub limit: u64,
}
impl From<QuotaResourceRef<'_>> for QuotaResource {
fn from(resource: QuotaResourceRef<'_>) -> Self {
Self {
name: resource.name.into(),
usage: resource.usage,
limit: resource.limit,
}
}
}
impl QuotaResource {
/// Returns the usage percentage of a QuotaResource.
pub fn get_usage_percentage(&self) -> u64 {
self.usage
.saturating_mul(100)
.checked_div(self.limit)
// Assume that if `limit` is 0, this means that storage is unlimited:
.unwrap_or(0)
}
}
/// 5.1. QUOTA Response (<https://tools.ietf.org/html/rfc2087#section-5.1>)
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct Quota {
/// quota root name
pub root_name: String,
/// quota resources for this quota
pub resources: Vec<QuotaResource>,
}
impl From<QuotaRef<'_>> for Quota {
fn from(quota: QuotaRef<'_>) -> Self {
Self {
root_name: quota.root_name.to_string(),
resources: quota.resources.iter().map(|r| r.clone().into()).collect(),
}
}
}
/// 5.2. QUOTAROOT Response (<https://tools.ietf.org/html/rfc2087#section-5.2>)
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
pub struct QuotaRoot {
/// mailbox name
pub mailbox_name: String,
/// zero or more quota root names
pub quota_root_names: Vec<String>,
}
impl From<QuotaRootRef<'_>> for QuotaRoot {
fn from(root: QuotaRootRef<'_>) -> Self {
Self {
mailbox_name: root.mailbox_name.to_string(),
quota_root_names: root
.quota_root_names
.iter()
.map(|n| n.to_string())
.collect(),
}
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/name.rs | src/types/name.rs | pub use imap_proto::types::NameAttribute;
use imap_proto::{MailboxDatum, Response};
use self_cell::self_cell;
use crate::types::ResponseData;
self_cell!(
/// A name that matches a `LIST` or `LSUB` command.
pub struct Name {
owner: Box<ResponseData>,
#[covariant]
dependent: InnerName,
}
impl { Debug }
);
#[derive(PartialEq, Eq, Debug)]
pub struct InnerName<'a> {
attributes: Vec<NameAttribute<'a>>,
delimiter: Option<&'a str>,
name: &'a str,
}
impl Name {
pub(crate) fn from_mailbox_data(resp: ResponseData) -> Self {
Name::new(Box::new(resp), |response| match response.parsed() {
Response::MailboxData(MailboxDatum::List {
name_attributes,
delimiter,
name,
}) => InnerName {
attributes: name_attributes.to_owned(),
delimiter: delimiter.as_deref(),
name,
},
_ => panic!("cannot construct from non mailbox data"),
})
}
/// Attributes of this name.
pub fn attributes(&self) -> &[NameAttribute<'_>] {
&self.borrow_dependent().attributes[..]
}
/// The hierarchy delimiter is a character used to delimit levels of hierarchy in a mailbox
/// name. A client can use it to create child mailboxes, and to search higher or lower levels
/// of naming hierarchy. All children of a top-level hierarchy node use the same
/// separator character. `None` means that no hierarchy exists; the name is a "flat" name.
pub fn delimiter(&self) -> Option<&str> {
self.borrow_dependent().delimiter
}
/// The name represents an unambiguous left-to-right hierarchy, and are valid for use as a
/// reference in `LIST` and `LSUB` commands. Unless [`NameAttribute::NoSelect`] is indicated,
/// the name is also valid as an argument for commands, such as `SELECT`, that accept mailbox
/// names.
pub fn name(&self) -> &str {
self.borrow_dependent().name
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/id_generator.rs | src/types/id_generator.rs | use imap_proto::RequestId;
/// Request ID generator.
#[derive(Debug)]
pub struct IdGenerator {
/// Last returned ID.
next: u64,
}
impl IdGenerator {
/// Creates a new request ID generator.
pub fn new() -> Self {
Self { next: 0 }
}
}
impl Default for IdGenerator {
fn default() -> Self {
Self::new()
}
}
impl Iterator for IdGenerator {
type Item = RequestId;
fn next(&mut self) -> Option<Self::Item> {
self.next += 1;
Some(RequestId(format!("A{:04}", self.next % 10_000)))
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/request.rs | src/types/request.rs | use imap_proto::RequestId;
#[derive(Debug, Eq, PartialEq)]
pub struct Request(pub Option<RequestId>, pub Vec<u8>);
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/capabilities.rs | src/types/capabilities.rs | use imap_proto::types::Capability as CapabilityRef;
use std::collections::hash_set::Iter;
use std::collections::HashSet;
const IMAP4REV1_CAPABILITY: &str = "IMAP4rev1";
const AUTH_CAPABILITY_PREFIX: &str = "AUTH=";
/// List of available Capabilities.
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum Capability {
/// The crucial imap capability.
Imap4rev1,
/// Auth type capability.
Auth(String),
/// Any other atoms.
Atom(String),
}
impl From<&CapabilityRef<'_>> for Capability {
fn from(c: &CapabilityRef<'_>) -> Self {
match c {
CapabilityRef::Imap4rev1 => Capability::Imap4rev1,
CapabilityRef::Auth(s) => Capability::Auth(s.clone().into_owned()),
CapabilityRef::Atom(s) => Capability::Atom(s.clone().into_owned()),
}
}
}
/// From [section 7.2.1 of RFC 3501](https://tools.ietf.org/html/rfc3501#section-7.2.1).
///
/// A list of capabilities that the server supports.
/// The capability list will include the atom "IMAP4rev1".
///
/// In addition, all servers implement the `STARTTLS`, `LOGINDISABLED`, and `AUTH=PLAIN` (described
/// in [IMAP-TLS](https://tools.ietf.org/html/rfc2595)) capabilities. See the [Security
/// Considerations section of the RFC](https://tools.ietf.org/html/rfc3501#section-11) for
/// important information.
///
/// A capability name which begins with `AUTH=` indicates that the server supports that particular
/// authentication mechanism.
///
/// The `LOGINDISABLED` capability indicates that the `LOGIN` command is disabled, and that the
/// server will respond with a [`crate::error::Error::No`] response to any attempt to use the `LOGIN`
/// command even if the user name and password are valid. An IMAP client MUST NOT issue the
/// `LOGIN` command if the server advertises the `LOGINDISABLED` capability.
///
/// Other capability names indicate that the server supports an extension, revision, or amendment
/// to the IMAP4rev1 protocol. Capability names either begin with `X` or they are standard or
/// standards-track [RFC 3501](https://tools.ietf.org/html/rfc3501) extensions, revisions, or
/// amendments registered with IANA.
///
/// Client implementations SHOULD NOT require any capability name other than `IMAP4rev1`, and MUST
/// ignore any unknown capability names.
pub struct Capabilities(pub(crate) HashSet<Capability>);
impl Capabilities {
/// Check if the server has the given capability.
pub fn has(&self, cap: &Capability) -> bool {
self.0.contains(cap)
}
/// Check if the server has the given capability via str.
pub fn has_str<S: AsRef<str>>(&self, cap: S) -> bool {
let s = cap.as_ref();
if s.eq_ignore_ascii_case(IMAP4REV1_CAPABILITY) {
return self.has(&Capability::Imap4rev1);
}
if s.len() > AUTH_CAPABILITY_PREFIX.len() {
let (pre, val) = s.split_at(AUTH_CAPABILITY_PREFIX.len());
if pre.eq_ignore_ascii_case(AUTH_CAPABILITY_PREFIX) {
return self.has(&Capability::Auth(val.into())); // TODO: avoid clone
}
}
self.has(&Capability::Atom(s.into())) // TODO: avoid clone
}
/// Iterate over all the server's capabilities
pub fn iter(&self) -> Iter<'_, Capability> {
self.0.iter()
}
/// Returns how many capabilities the server has.
pub fn len(&self) -> usize {
self.0.len()
}
/// Returns true if the server purports to have no capabilities.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/src/types/response_data.rs | src/types/response_data.rs | use std::fmt;
use bytes::BytesMut;
use imap_proto::{RequestId, Response};
use self_cell::self_cell;
self_cell!(
pub struct ResponseData {
owner: BytesMut,
#[covariant]
dependent: Response,
}
);
impl std::cmp::PartialEq for ResponseData {
fn eq(&self, other: &Self) -> bool {
self.parsed() == other.parsed()
}
}
impl std::cmp::Eq for ResponseData {}
impl fmt::Debug for ResponseData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ResponseData")
.field("raw", &self.borrow_owner().len())
.field("response", self.borrow_dependent())
.finish()
}
}
impl ResponseData {
pub fn request_id(&self) -> Option<&RequestId> {
match self.borrow_dependent() {
Response::Done { ref tag, .. } => Some(tag),
_ => None,
}
}
pub fn parsed(&self) -> &Response<'_> {
self.borrow_dependent()
}
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/examples/src/bin/idle.rs | examples/src/bin/idle.rs | use std::env;
use std::time::Duration;
use anyhow::{bail, Result};
use async_imap::extensions::idle::IdleResponse::*;
use futures::StreamExt;
#[cfg(feature = "runtime-async-std")]
use async_std::{net::TcpStream, task, task::sleep};
#[cfg(feature = "runtime-tokio")]
use tokio::{net::TcpStream, task, time::sleep};
#[cfg_attr(feature = "runtime-tokio", tokio::main)]
#[cfg_attr(feature = "runtime-async-std", async_std::main)]
async fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 4 {
eprintln!("need three arguments: imap-server login password");
bail!("need three arguments");
} else {
fetch_and_idle(&args[1], &args[2], &args[3]).await?;
Ok(())
}
}
async fn fetch_and_idle(imap_server: &str, login: &str, password: &str) -> Result<()> {
let imap_addr = (imap_server, 993);
let tcp_stream = TcpStream::connect(imap_addr).await?;
let tls = async_native_tls::TlsConnector::new();
let tls_stream = tls.connect(imap_server, tcp_stream).await?;
let client = async_imap::Client::new(tls_stream);
println!("-- connected to {}:{}", imap_addr.0, imap_addr.1);
// the client we have here is unauthenticated.
// to do anything useful with the e-mails, we need to log in
let mut session = client.login(login, password).await.map_err(|e| e.0)?;
println!("-- logged in a {}", login);
// we want to fetch some messages from the INBOX
session.select("INBOX").await?;
println!("-- INBOX selected");
// fetch flags from all messages
let msg_stream = session.fetch("1:*", "(FLAGS )").await?;
let msgs = msg_stream.collect::<Vec<_>>().await;
println!("-- number of fetched msgs: {:?}", msgs.len());
// init idle session
println!("-- initializing idle");
let mut idle = session.idle();
idle.init().await?;
println!("-- idle async wait");
let (idle_wait, interrupt) = idle.wait();
/*
let stdin = io::stdin();
let mut line = String::new();
stdin.read_line(&mut line).await?;
println!("-- read line: {}", line);
*/
task::spawn(async move {
println!("-- thread: waiting for 30s");
sleep(Duration::from_secs(30)).await;
println!("-- thread: waited 30 secs, now interrupting idle");
drop(interrupt);
});
let idle_result = idle_wait.await?;
match idle_result {
ManualInterrupt => {
println!("-- IDLE manually interrupted");
}
Timeout => {
println!("-- IDLE timed out");
}
NewData(data) => {
let s = String::from_utf8(data.borrow_owner().to_vec()).unwrap();
println!("-- IDLE data:\n{}", s);
}
}
// return the session after we are done with it
println!("-- sending DONE");
let mut session = idle.done().await?;
// be nice to the server and log out
println!("-- logging out");
session.logout().await?;
Ok(())
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/examples/src/bin/futures.rs | examples/src/bin/futures.rs | use std::env;
use anyhow::{bail, Result};
use futures::TryStreamExt;
#[cfg(feature = "runtime-async-std")]
use async_std::net::TcpStream;
#[cfg(feature = "runtime-tokio")]
use tokio::net::TcpStream;
fn main() -> Result<()> {
futures::executor::block_on(async {
let args: Vec<String> = env::args().collect();
if args.len() != 4 {
eprintln!("need three arguments: imap-server login password");
bail!("need three arguments");
} else {
let res = fetch_inbox_top(&args[1], &args[2], &args[3]).await?;
println!("**result:\n{}", res.unwrap());
Ok(())
}
})
}
async fn fetch_inbox_top(imap_server: &str, login: &str, password: &str) -> Result<Option<String>> {
let imap_addr = (imap_server, 993);
let tcp_stream = TcpStream::connect(imap_addr).await?;
let tls = async_native_tls::TlsConnector::new();
let tls_stream = tls.connect(imap_server, tcp_stream).await?;
let client = async_imap::Client::new(tls_stream);
println!("-- connected to {}:{}", imap_server, 993);
// the client we have here is unauthenticated.
// to do anything useful with the e-mails, we need to log in
let mut imap_session = client.login(login, password).await.map_err(|e| e.0)?;
println!("-- logged in a {}", login);
// we want to fetch the first email in the INBOX mailbox
imap_session.select("INBOX").await?;
println!("-- INBOX selected");
// fetch message number 1 in this mailbox, along with its RFC822 field.
// RFC 822 dictates the format of the body of e-mails
let messages_stream = imap_session.fetch("1", "RFC822").await?;
let messages: Vec<_> = messages_stream.try_collect().await?;
let message = if let Some(m) = messages.first() {
m
} else {
return Ok(None);
};
// extract the message's body
let body = message.body().expect("message did not have a body!");
let body = std::str::from_utf8(body)
.expect("message was not valid utf-8")
.to_string();
println!("-- 1 message received, logging out");
// be nice to the server and log out
imap_session.logout().await?;
Ok(Some(body))
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/examples/src/bin/integration.rs | examples/src/bin/integration.rs | use std::borrow::Cow;
use std::time::Duration;
use anyhow::{Context as _, Result};
use async_imap::Session;
use async_native_tls::TlsConnector;
use async_smtp::{SendableEmail, SmtpClient, SmtpTransport};
#[cfg(feature = "runtime-async-std")]
use async_std::{net::TcpStream, task, task::sleep};
use futures::{StreamExt, TryStreamExt};
#[cfg(feature = "runtime-tokio")]
use tokio::{net::TcpStream, task, time::sleep};
fn tls() -> TlsConnector {
TlsConnector::new()
.danger_accept_invalid_hostnames(true)
.danger_accept_invalid_certs(true)
}
fn test_host() -> String {
std::env::var("TEST_HOST").unwrap_or_else(|_| "127.0.0.1".into())
}
async fn session(user: &str) -> Result<Session<async_native_tls::TlsStream<TcpStream>>> {
let host = test_host();
let addr = (host.as_str(), 3993);
let tcp_stream = TcpStream::connect(addr).await?;
let tls = tls();
let tls_stream = tls.connect("imap.example.com", tcp_stream).await?;
let mut client = async_imap::Client::new(tls_stream);
let _greeting = client
.read_response()
.await?
.context("unexpected end of stream, expected greeting")?;
let session = client
.login(user, user)
.await
.map_err(|(err, _client)| err)?;
Ok(session)
}
// ignored because of https://github.com/greenmail-mail-test/greenmail/issues/135
async fn _connect_insecure_then_secure() -> Result<()> {
let tcp_stream = TcpStream::connect((test_host().as_ref(), 3143)).await?;
let tls = tls();
let mut client = async_imap::Client::new(tcp_stream);
let _greeting = client
.read_response()
.await?
.context("unexpected end of stream, expected greeting")?;
client.run_command_and_check_ok("STARTTLS", None).await?;
let stream = client.into_inner();
let tls_stream = tls.connect("imap.example.com", stream).await?;
let _client = async_imap::Client::new(tls_stream);
Ok(())
}
async fn smtp(user: &str) -> Result<SmtpTransport<async_native_tls::TlsStream<TcpStream>>> {
let host = test_host();
let tcp_stream = TcpStream::connect((host.as_str(), 3465)).await?;
let tls = tls();
let tls_stream = tls.connect("localhost", tcp_stream).await?;
let client = SmtpClient::new().smtp_utf8(true);
let mut transport = SmtpTransport::new(client, tls_stream).await?;
let credentials =
async_smtp::authentication::Credentials::new(user.to_string(), user.to_string());
let mechanism = vec![
async_smtp::authentication::Mechanism::Plain,
async_smtp::authentication::Mechanism::Login,
];
transport.try_login(&credentials, &mechanism).await?;
Ok(transport)
}
async fn login() -> Result<()> {
session("readonly-test@localhost").await?;
Ok(())
}
async fn logout() -> Result<()> {
let mut s = session("readonly-test@localhost").await?;
s.logout().await?;
Ok(())
}
async fn inbox_zero() -> Result<()> {
// https://github.com/greenmail-mail-test/greenmail/issues/265
let mut s = session("readonly-test@localhost").await?;
s.select("INBOX").await?;
let inbox = s.search("ALL").await?;
assert_eq!(inbox.len(), 0);
Ok(())
}
fn make_email(to: &str) -> SendableEmail {
let message_id = "abc";
async_smtp::SendableEmail::new(
async_smtp::Envelope::new(
Some("sender@localhost".parse().unwrap()),
vec![to.parse().unwrap()],
)
.unwrap(),
format!("To: <{}>\r\nFrom: <sender@localhost>\r\nMessage-ID: <{}.msg@localhost>\r\nSubject: My first e-mail\r\n\r\nHello world from SMTP", to, message_id),
)
}
async fn inbox() -> Result<()> {
let to = "inbox@localhost";
// first log in so we'll see the unsolicited e-mails
let mut c = session(to).await?;
c.select("INBOX").await?;
println!("sending");
let mut s = smtp(to).await?;
// then send the e-mail
let mail = make_email(to);
s.send(mail).await?;
println!("searching");
// now we should see the e-mail!
let inbox = c.search("ALL").await?;
// and the one message should have the first message sequence number
assert_eq!(inbox.len(), 1);
assert!(inbox.contains(&1));
// we should also get two unsolicited responses: Exists and Recent
c.noop().await.unwrap();
println!("noop done");
let mut unsolicited = Vec::new();
while !c.unsolicited_responses.is_empty() {
unsolicited.push(c.unsolicited_responses.recv().await.unwrap());
}
assert_eq!(unsolicited.len(), 2);
assert!(unsolicited
.iter()
.any(|m| m == &async_imap::types::UnsolicitedResponse::Exists(1)));
assert!(unsolicited
.iter()
.any(|m| m == &async_imap::types::UnsolicitedResponse::Recent(1)));
println!("fetching");
// let's see that we can also fetch the e-mail
let fetch: Vec<_> = c
.fetch("1", "(ALL UID)")
.await
.unwrap()
.try_collect()
.await
.unwrap();
assert_eq!(fetch.len(), 1);
let fetch = &fetch[0];
assert_eq!(fetch.message, 1);
assert_ne!(fetch.uid, None);
assert_eq!(fetch.size, Some(21));
let e = fetch.envelope().unwrap();
assert_eq!(e.subject, Some(Cow::Borrowed(&b"My first e-mail"[..])));
assert_ne!(e.from, None);
assert_eq!(e.from.as_ref().unwrap().len(), 1);
let from = &e.from.as_ref().unwrap()[0];
assert_eq!(from.mailbox, Some(Cow::Borrowed(&b"sender"[..])));
assert_eq!(from.host, Some(Cow::Borrowed(&b"localhost"[..])));
assert_ne!(e.to, None);
assert_eq!(e.to.as_ref().unwrap().len(), 1);
let to = &e.to.as_ref().unwrap()[0];
assert_eq!(to.mailbox, Some(Cow::Borrowed(&b"inbox"[..])));
assert_eq!(to.host, Some(Cow::Borrowed(&b"localhost"[..])));
let date_opt = fetch.internal_date();
assert!(date_opt.is_some());
// and let's delete it to clean up
c.store("1", "+FLAGS (\\Deleted)")
.await
.unwrap()
.collect::<Vec<_>>()
.await;
c.expunge().await.unwrap().collect::<Vec<_>>().await;
// the e-mail should be gone now
let inbox = c.search("ALL").await?;
assert_eq!(inbox.len(), 0);
Ok(())
}
async fn inbox_uid() -> Result<()> {
let to = "inbox-uid@localhost";
// first log in so we'll see the unsolicited e-mails
let mut c = session(to).await?;
c.select("INBOX").await?;
// then send the e-mail
let mut s = smtp(to).await?;
let e = make_email(to);
s.send(e).await?;
// now we should see the e-mail!
let inbox = c.uid_search("ALL").await?;
// and the one message should have the first message sequence number
assert_eq!(inbox.len(), 1);
let uid = inbox.into_iter().next().unwrap();
// we should also get two unsolicited responses: Exists and Recent
c.noop().await?;
let mut unsolicited = Vec::new();
while !c.unsolicited_responses.is_empty() {
unsolicited.push(c.unsolicited_responses.recv().await?);
}
assert_eq!(unsolicited.len(), 2);
assert!(unsolicited
.iter()
.any(|m| m == &async_imap::types::UnsolicitedResponse::Exists(1)));
assert!(unsolicited
.iter()
.any(|m| m == &async_imap::types::UnsolicitedResponse::Recent(1)));
// let's see that we can also fetch the e-mail
let fetch: Vec<_> = c
.uid_fetch(format!("{}", uid), "(ALL UID)")
.await?
.try_collect()
.await?;
assert_eq!(fetch.len(), 1);
let fetch = &fetch[0];
assert_eq!(fetch.uid, Some(uid));
let e = fetch.envelope().unwrap();
assert_eq!(e.subject, Some(Cow::Borrowed(&b"My first e-mail"[..])));
let date_opt = fetch.internal_date();
assert!(date_opt.is_some());
// and let's delete it to clean up
c.uid_store(format!("{}", uid), "+FLAGS (\\Deleted)")
.await?
.collect::<Vec<_>>()
.await;
c.expunge().await?.collect::<Vec<_>>().await;
// the e-mail should be gone now
let inbox = c.search("ALL").await?;
assert_eq!(inbox.len(), 0);
Ok(())
}
async fn _list() -> Result<()> {
let mut s = session("readonly-test@localhost").await?;
s.select("INBOX").await?;
let subdirs: Vec<_> = s.list(None, Some("%")).await?.collect().await;
assert_eq!(subdirs.len(), 0);
// TODO: make a subdir
Ok(())
}
// Greenmail does not support IDLE :(
async fn _idle() -> Result<()> {
let mut session = session("idle-test@localhost").await?;
// get that inbox
let res = session.select("INBOX").await?;
println!("selected: {:#?}", res);
// fetchy fetch
let msg_stream = session.fetch("1:3", "(FLAGS BODY.PEEK[])").await?;
let msgs = msg_stream.collect::<Vec<_>>().await;
println!("msgs: {:?}", msgs.len());
// Idle session
println!("starting idle");
let mut idle = session.idle();
idle.init().await?;
let (idle_wait, interrupt) = idle.wait_with_timeout(std::time::Duration::from_secs(30));
println!("idle wait");
task::spawn(async move {
println!("waiting for 1s");
sleep(Duration::from_secs(2)).await;
println!("interrupting idle");
drop(interrupt);
});
let idle_result = idle_wait.await;
println!("idle result: {:#?}", &idle_result);
// return the session after we are done with it
let mut session = idle.done().await?;
println!("logging out");
session.logout().await?;
Ok(())
}
#[cfg_attr(feature = "runtime-tokio", tokio::main)]
#[cfg_attr(feature = "runtime-async-std", async_std::main)]
async fn main() -> Result<()> {
login().await?;
logout().await?;
inbox_zero().await?;
inbox().await?;
inbox_uid().await?;
Ok(())
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/examples/src/bin/gmail_oauth2.rs | examples/src/bin/gmail_oauth2.rs | use anyhow::Result;
use futures::StreamExt;
#[cfg(feature = "runtime-async-std")]
use async_std::net::TcpStream;
#[cfg(feature = "runtime-tokio")]
use tokio::net::TcpStream;
struct GmailOAuth2 {
user: String,
access_token: String,
}
impl async_imap::Authenticator for &GmailOAuth2 {
type Response = String;
fn process(&mut self, _data: &[u8]) -> Self::Response {
format!(
"user={}\x01auth=Bearer {}\x01\x01",
self.user, self.access_token
)
}
}
#[cfg_attr(feature = "runtime-tokio", tokio::main)]
#[cfg_attr(feature = "runtime-async-std", async_std::main)]
async fn main() -> Result<()> {
let gmail_auth = GmailOAuth2 {
user: String::from("sombody@gmail.com"),
access_token: String::from("<access_token>"),
};
let domain = "imap.gmail.com";
let port = 993;
let socket_addr = (domain, port);
let tcp_stream = TcpStream::connect(socket_addr).await?;
let tls = async_native_tls::TlsConnector::new();
let tls_stream = tls.connect(domain, tcp_stream).await?;
let client = async_imap::Client::new(tls_stream);
let mut imap_session = match client.authenticate("XOAUTH2", &gmail_auth).await {
Ok(c) => c,
Err((e, _unauth_client)) => {
println!("error authenticating: {}", e);
return Err(e.into());
}
};
match imap_session.select("INBOX").await {
Ok(mailbox) => println!("{}", mailbox),
Err(e) => println!("Error selecting INBOX: {}", e),
};
{
let mut msgs = imap_session.fetch("2", "body[text]").await.map_err(|e| {
eprintln!("Error Fetching email 2: {}", e);
e
})?;
while let Some(msg) = msgs.next().await {
print!("{:?}", msg?);
}
}
imap_session.logout().await?;
Ok(())
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
chatmail/async-imap | https://github.com/chatmail/async-imap/blob/15f80ea95b96f26cec37f45d194b4345957bc838/examples/src/bin/basic.rs | examples/src/bin/basic.rs | use std::env;
use anyhow::{bail, Result};
use futures::TryStreamExt;
#[cfg(feature = "runtime-async-std")]
use async_std::net::TcpStream;
#[cfg(feature = "runtime-tokio")]
use tokio::net::TcpStream;
#[cfg_attr(feature = "runtime-tokio", tokio::main)]
#[cfg_attr(feature = "runtime-async-std", async_std::main)]
async fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 4 {
eprintln!("need three arguments: imap-server login password");
bail!("need three arguments");
} else {
let res = fetch_inbox_top(&args[1], &args[2], &args[3]).await?;
println!("**result:\n{}", res.unwrap());
Ok(())
}
}
async fn fetch_inbox_top(imap_server: &str, login: &str, password: &str) -> Result<Option<String>> {
let imap_addr = (imap_server, 993);
let tcp_stream = TcpStream::connect(imap_addr).await?;
let tls = async_native_tls::TlsConnector::new();
let tls_stream = tls.connect(imap_server, tcp_stream).await?;
let client = async_imap::Client::new(tls_stream);
println!("-- connected to {}:{}", imap_addr.0, imap_addr.1);
// the client we have here is unauthenticated.
// to do anything useful with the e-mails, we need to log in
let mut imap_session = client.login(login, password).await.map_err(|e| e.0)?;
println!("-- logged in a {}", login);
// we want to fetch the first email in the INBOX mailbox
imap_session.select("INBOX").await?;
println!("-- INBOX selected");
// fetch message number 1 in this mailbox, along with its RFC822 field.
// RFC 822 dictates the format of the body of e-mails
let messages_stream = imap_session.fetch("1", "RFC822").await?;
let messages: Vec<_> = messages_stream.try_collect().await?;
let message = if let Some(m) = messages.first() {
m
} else {
return Ok(None);
};
// extract the message's body
let body = message.body().expect("message did not have a body!");
let body = std::str::from_utf8(body)
.expect("message was not valid utf-8")
.to_string();
println!("-- 1 message received, logging out");
// be nice to the server and log out
imap_session.logout().await?;
Ok(Some(body))
}
| rust | Apache-2.0 | 15f80ea95b96f26cec37f45d194b4345957bc838 | 2026-01-04T20:25:22.717976Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/build.rs | build.rs | use std::io;
#[cfg(windows)] use winres::WindowsResource;
fn main() -> io::Result<()>
{
#[cfg(windows)] {
WindowsResource::new()
.set_icon("icon.ico")
.compile()?;
}
Ok(())
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/lib.rs | src/lib.rs | pub mod common;
pub mod config;
pub mod database;
pub mod tracker;
pub mod stats;
pub mod api;
pub mod http;
pub mod udp;
pub mod structs; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/structs.rs | src/structs.rs | use clap::Parser;
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// Create config.toml file if not exists or is broken
#[arg(long)]
pub create_config: bool,
/// Create the database for the engine that is used in the config.toml
#[arg(long)]
pub create_database: bool,
/// Create a development self-signed key and certificate file in PEM format
#[arg(long)]
pub create_selfsigned: bool,
/// Add an extra domain/subdomain into the certificate, for development
#[arg(long, requires("create_selfsigned"), default_value = "localhost")]
pub selfsigned_domain: String,
/// Give the filename of the key file of the certificate, default key.pem
#[arg(long, requires("create_selfsigned"), default_value = "key.pem")]
pub selfsigned_keyfile: String,
/// Give the filename of the certificate file, default cert.pem
#[arg(long, requires("create_selfsigned"), default_value = "cert.pem")]
pub selfsigned_certfile: String,
/// Create export files of the data from the database, useful for migration or backup
#[arg(long)]
pub export: bool,
/// Give the filename of the JSON file for torrents, default torrents.json
#[arg(long, requires("export"), default_value = "torrents.json")]
pub export_file_torrents: String,
/// Give the filename of the JSON file for whitelists, default whitelists.json
#[arg(long, requires("export"), default_value = "whitelists.json")]
pub export_file_whitelists: String,
/// Give the filename of the JSON file for blacklists, default blacklists.json
#[arg(long, requires("export"), default_value = "blacklists.json")]
pub export_file_blacklists: String,
/// Give the filename of the JSON file for keys, default keys.json
#[arg(long, requires("export"), default_value = "keys.json")]
pub export_file_keys: String,
/// Give the filename of the JSON file for users, default users.json
#[arg(long, requires("export"), default_value = "users.json")]
pub export_file_users: String,
/// Import data from JSON files
#[arg(long)]
pub import: bool,
/// Give the filename of the JSON file for torrents, default torrents.json
#[arg(long, requires("export"), default_value = "torrents.json")]
pub import_file_torrents: String,
/// Give the filename of the JSON file for whitelists, default whitelists.json
#[arg(long, requires("export"), default_value = "whitelists.json")]
pub import_file_whitelists: String,
/// Give the filename of the JSON file for blacklists, default blacklists.json
#[arg(long, requires("export"), default_value = "blacklists.json")]
pub import_file_blacklists: String,
/// Give the filename of the JSON file for keys, default keys.json
#[arg(long, requires("export"), default_value = "keys.json")]
pub import_file_keys: String,
/// Give the filename of the JSON file for users, default users.json
#[arg(long, requires("export"), default_value = "users.json")]
pub import_file_users: String,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/main.rs | src/main.rs | use std::mem;
use std::net::SocketAddr;
use std::process::exit;
use std::sync::Arc;
use std::time::Duration;
use async_std::task;
use clap::Parser;
use futures_util::future::try_join_all;
use log::{error, info};
use parking_lot::deadlock;
use sentry::ClientInitGuard;
use tokio::runtime::Builder;
use tokio_shutdown::Shutdown;
use torrust_actix::api::api::api_service;
use torrust_actix::common::common::{setup_logging, shutdown_waiting, udp_check_host_and_port_used};
use torrust_actix::config::structs::configuration::Configuration;
use torrust_actix::http::http::{http_check_host_and_port_used, http_service};
use torrust_actix::structs::Cli;
use torrust_actix::stats::enums::stats_event::StatsEvent;
use torrust_actix::tracker::structs::torrent_tracker::TorrentTracker;
use torrust_actix::udp::udp::udp_service;
#[tracing::instrument(level = "debug")]
fn main() -> std::io::Result<()>
{
let args = Cli::parse();
let config = match Configuration::load_from_file(args.create_config) {
Ok(config) => Arc::new(config),
Err(_) => exit(101)
};
setup_logging(&config);
info!("{} - Version: {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
#[warn(unused_variables)]
let _sentry_guard: ClientInitGuard;
if config.sentry_config.enabled {
_sentry_guard = sentry::init((config.sentry_config.dsn.clone(), sentry::ClientOptions {
release: sentry::release_name!(),
debug: config.sentry_config.debug,
sample_rate: config.sentry_config.sample_rate,
max_breadcrumbs: config.sentry_config.max_breadcrumbs,
attach_stacktrace: config.sentry_config.attach_stacktrace,
send_default_pii: config.sentry_config.send_default_pii,
traces_sample_rate: config.sentry_config.traces_sample_rate,
session_mode: sentry::SessionMode::Request,
auto_session_tracking: true,
..Default::default()
}));
}
Builder::new_multi_thread()
.enable_all()
.build()?
.block_on(async {
let tracker = Arc::new(TorrentTracker::new(config.clone(), args.create_database).await);
let tracker_config = tracker.config.tracker_config.clone();
let db_config = tracker.config.database.clone();
if db_config.persistent {
tracker.load_torrents(tracker.clone()).await;
if tracker_config.whitelist_enabled {
tracker.load_whitelist(tracker.clone()).await;
}
if tracker_config.blacklist_enabled {
tracker.load_blacklist(tracker.clone()).await;
}
if tracker_config.keys_enabled {
tracker.load_keys(tracker.clone()).await;
}
if tracker_config.users_enabled {
tracker.load_users(tracker.clone()).await;
}
if db_config.update_peers && !tracker.reset_seeds_peers(tracker.clone()).await {
panic!("[RESET SEEDS PEERS] Unable to continue loading");
}
} else {
tracker.set_stats(StatsEvent::Completed, config.tracker_config.total_downloads as i64);
}
if args.create_selfsigned { tracker.cert_gen(&args).await; }
if args.export { tracker.export(&args, tracker.clone()).await; }
if args.import { tracker.import(&args, tracker.clone()).await; }
let tokio_core = Builder::new_multi_thread().thread_name("core").worker_threads(9).enable_all().build()?;
let tokio_shutdown = Shutdown::new().expect("shutdown creation works on first call");
let deadlocks_handler = tokio_shutdown.clone();
tokio_core.spawn(async move {
info!("[BOOT] Starting thread for deadlocks...");
let mut interval = tokio::time::interval(Duration::from_secs(30));
loop {
tokio::select! {
_ = interval.tick() => {
let deadlocks = deadlock::check_deadlock();
if !deadlocks.is_empty() {
info!("[DEADLOCK] Found {} deadlocks", deadlocks.len());
for (i, threads) in deadlocks.iter().enumerate() {
info!("[DEADLOCK] #{i}");
for t in threads {
info!("[DEADLOCK] Thread ID: {:#?}", t.thread_id());
info!("[DEADLOCK] {:#?}", t.backtrace());
sentry::capture_message(&format!("{:#?}", t.backtrace()), sentry::Level::Error);
}
}
}
}
_ = deadlocks_handler.handle() => {
info!("[BOOT] Shutting down thread for deadlocks...");
return;
}
}
}
});
let mut api_futures = Vec::new();
let mut apis_futures = Vec::new();
for api_server_object in &config.api_server {
if api_server_object.enabled {
http_check_host_and_port_used(api_server_object.bind_address.clone());
let address: SocketAddr = api_server_object.bind_address.parse().unwrap();
let (handle, future) = api_service(
address,
tracker.clone(),
api_server_object.clone()
).await;
if api_server_object.ssl {
apis_futures.push((handle, future));
} else {
api_futures.push((handle, future));
}
}
}
if !api_futures.is_empty() {
let (handles, futures): (Vec<_>, Vec<_>) = api_futures.into_iter().unzip();
tokio_core.spawn(async move {
let _ = try_join_all(futures).await;
drop(handles);
});
}
if !apis_futures.is_empty() {
let (handles, futures): (Vec<_>, Vec<_>) = apis_futures.into_iter().unzip();
tokio_core.spawn(async move {
let _ = try_join_all(futures).await;
drop(handles);
});
}
let mut http_futures = Vec::new();
let mut https_futures = Vec::new();
for http_server_object in &config.http_server {
if http_server_object.enabled {
http_check_host_and_port_used(http_server_object.bind_address.clone());
let address: SocketAddr = http_server_object.bind_address.parse().unwrap();
let (handle, future) = http_service(
address,
tracker.clone(),
http_server_object.clone()
).await;
if http_server_object.ssl {
https_futures.push((handle, future));
} else {
http_futures.push((handle, future));
}
}
}
if !http_futures.is_empty() {
let (handles, futures): (Vec<_>, Vec<_>) = http_futures.into_iter().unzip();
tokio_core.spawn(async move {
let _ = try_join_all(futures).await;
drop(handles);
});
}
if !https_futures.is_empty() {
let (handles, futures): (Vec<_>, Vec<_>) = https_futures.into_iter().unzip();
tokio_core.spawn(async move {
let _ = try_join_all(futures).await;
drop(handles);
});
}
let (udp_tx, udp_rx) = tokio::sync::watch::channel(false);
let mut udp_tokio_threads = Vec::new();
let mut udp_futures = Vec::new();
for udp_server_object in &config.udp_server {
if udp_server_object.enabled {
udp_check_host_and_port_used(udp_server_object.bind_address.clone());
let address: SocketAddr = udp_server_object.bind_address.parse().unwrap();
let udp_threads: usize = udp_server_object.udp_threads;
let worker_threads: usize = udp_server_object.worker_threads;
let tokio_udp = Arc::new(Builder::new_multi_thread()
.thread_name("udp")
.worker_threads(udp_threads)
.enable_all()
.build()?);
let udp_future = udp_service(
address,
udp_threads,
worker_threads,
udp_server_object.receive_buffer_size,
udp_server_object.send_buffer_size,
udp_server_object.reuse_address,
tracker.clone(),
udp_rx.clone(),
tokio_udp.clone()
).await;
udp_futures.push(udp_future);
udp_tokio_threads.push(tokio_udp);
}
}
let stats_handler = tokio_shutdown.clone();
let tracker_spawn_stats = tracker.clone();
let console_interval = tracker_spawn_stats.config.log_console_interval;
info!("[BOOT] Starting thread for console updates with {console_interval} seconds delay...");
tokio_core.spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(console_interval));
let mut last_udp: Option<(i64,i64,i64,i64,i64,i64,i64)> = None;
loop {
tokio::select! {
_ = interval.tick() => {
tracker_spawn_stats.set_stats(StatsEvent::TimestampSave, chrono::Utc::now().timestamp() + 60);
let stats = tracker_spawn_stats.get_stats();
info!(
"[STATS] Torrents: {} - Updates: {} - Seeds: {} - Peers: {} - Completed: {} | \
WList: {} - WList Updates: {} - BLists: {} - BLists Updates: {} - Keys: {} - Keys Updates {}",
stats.torrents, stats.torrents_updates, stats.seeds, stats.peers, stats.completed,
stats.whitelist, stats.whitelist_updates, stats.blacklist, stats.blacklist_updates,
stats.keys, stats.keys_updates
);
info!(
"[STATS TCP] IPv4: Conn:{} API:{} A:{} S:{} F:{} 404:{} | IPv6: Conn:{} API:{} A:{} S:{} F:{} 404:{}",
stats.tcp4_connections_handled, stats.tcp4_api_handled, stats.tcp4_announces_handled,
stats.tcp4_scrapes_handled, stats.tcp4_failure, stats.tcp4_not_found,
stats.tcp6_connections_handled, stats.tcp6_api_handled, stats.tcp6_announces_handled,
stats.tcp6_scrapes_handled, stats.tcp6_failure, stats.tcp6_not_found
);
let now = chrono::Utc::now().timestamp();
let (udp_c4_ps, udp_a4_ps, udp_s4_ps, udp_c6_ps, udp_a6_ps, udp_s6_ps) = if let Some((t,c4,a4,s4,c6,a6,s6)) = last_udp {
let dt = (now - t).max(1);
(
(stats.udp4_connections_handled - c4)/dt,
(stats.udp4_announces_handled - a4)/dt,
(stats.udp4_scrapes_handled - s4)/dt,
(stats.udp6_connections_handled - c6)/dt,
(stats.udp6_announces_handled - a6)/dt,
(stats.udp6_scrapes_handled - s6)/dt,
)
} else { (0,0,0,0,0,0) };
last_udp = Some((now, stats.udp4_connections_handled, stats.udp4_announces_handled, stats.udp4_scrapes_handled,
stats.udp6_connections_handled, stats.udp6_announces_handled, stats.udp6_scrapes_handled));
info!(
"[STATS UDP] IPv4: Conn:{} ({}s) A:{} ({}s) S:{} ({}s) IR:{} BR:{} | IPv6: Conn:{} ({}s) A:{} ({}s) S:{} ({}s) IR:{} BR:{} | Q:{}",
stats.udp4_connections_handled, udp_c4_ps, stats.udp4_announces_handled, udp_a4_ps, stats.udp4_scrapes_handled, udp_s4_ps,
stats.udp4_invalid_request, stats.udp4_bad_request,
stats.udp6_connections_handled, udp_c6_ps, stats.udp6_announces_handled, udp_a6_ps, stats.udp6_scrapes_handled, udp_s6_ps,
stats.udp6_invalid_request, stats.udp6_bad_request,
stats.udp_queue_len
);
}
_ = stats_handler.handle() => {
info!("[BOOT] Shutting down thread for console updates...");
return;
}
}
}
});
let tracker_cleanup_clone = tracker.clone();
let cleanup_handler = tokio_shutdown.clone();
let cleanup_interval = tracker_cleanup_clone.config.tracker_config.peers_cleanup_interval;
info!("[BOOT] Starting thread for peers cleanup with {cleanup_interval} seconds delay...");
let peers_timeout = tracker_cleanup_clone.config.tracker_config.peers_timeout;
let persistent = tracker_cleanup_clone.config.database.persistent;
let torrents_sharding = tracker_cleanup_clone.torrents_sharding.clone();
tokio_core.spawn(async move {
torrents_sharding.cleanup_threads(
tracker_cleanup_clone,
cleanup_handler,
Duration::from_secs(peers_timeout),
persistent
).await;
});
if tracker_config.keys_enabled {
let cleanup_keys_handler = tokio_shutdown.clone();
let tracker_spawn_cleanup_keys = tracker.clone();
let keys_interval = tracker_spawn_cleanup_keys.config.tracker_config.keys_cleanup_interval;
info!("[BOOT] Starting thread for keys cleanup with {keys_interval} seconds delay...");
tokio_core.spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(keys_interval));
loop {
tokio::select! {
_ = interval.tick() => {
tracker_spawn_cleanup_keys.set_stats(StatsEvent::TimestampKeysTimeout,
chrono::Utc::now().timestamp() + keys_interval as i64);
info!("[KEYS] Checking now for outdated keys.");
tracker_spawn_cleanup_keys.clean_keys();
info!("[KEYS] Keys cleaned up.");
}
_ = shutdown_waiting(Duration::from_secs(1), cleanup_keys_handler.clone()) => {
info!("[BOOT] Shutting down thread for keys cleanup...");
return;
}
}
}
});
}
if db_config.persistent {
let updates_handler = tokio_shutdown.clone();
let tracker_spawn_updates = tracker.clone();
let update_interval = tracker_spawn_updates.config.database.persistent_interval;
info!("[BOOT] Starting thread for database updates with {update_interval} seconds delay...");
tokio_core.spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(update_interval));
loop {
tokio::select! {
_ = interval.tick() => {
tracker_spawn_updates.set_stats(StatsEvent::TimestampSave,
chrono::Utc::now().timestamp() + update_interval as i64);
info!("[DATABASE UPDATES] Starting batch updates...");
let _ = tracker_spawn_updates.save_torrent_updates(tracker_spawn_updates.clone()).await;
if tracker_spawn_updates.config.tracker_config.whitelist_enabled {
let _ = tracker_spawn_updates.save_whitelist_updates(tracker_spawn_updates.clone()).await;
}
if tracker_spawn_updates.config.tracker_config.blacklist_enabled {
let _ = tracker_spawn_updates.save_blacklist_updates(tracker_spawn_updates.clone()).await;
}
if tracker_spawn_updates.config.tracker_config.keys_enabled {
let _ = tracker_spawn_updates.save_key_updates(tracker_spawn_updates.clone()).await;
}
if tracker_spawn_updates.config.tracker_config.users_enabled {
let _ = tracker_spawn_updates.save_user_updates(tracker_spawn_updates.clone()).await;
}
info!("[DATABASE UPDATES] Batch updates completed");
}
_ = shutdown_waiting(Duration::from_secs(1), updates_handler.clone()) => {
info!("[BOOT] Shutting down thread for updates...");
return;
}
}
}
});
}
tokio::select! {
_ = tokio::signal::ctrl_c() => {
info!("Shutdown request received, shutting down...");
let _ = udp_tx.send(true);
match try_join_all(udp_futures).await {
Ok(_) => {}
Err(error) => {
sentry::capture_error(&error);
error!("Errors happened on shutting down UDP sockets: {error}");
}
}
tokio_shutdown.handle().await;
task::sleep(Duration::from_secs(1)).await;
if db_config.persistent {
tracker.set_stats(StatsEvent::Completed, config.tracker_config.total_downloads as i64);
Configuration::save_from_config(tracker.config.clone(), "config.toml");
info!("Saving final data to database...");
let _ = tracker.save_torrent_updates(tracker.clone()).await;
if tracker_config.whitelist_enabled {
let _ = tracker.save_whitelist_updates(tracker.clone()).await;
}
if tracker_config.blacklist_enabled {
let _ = tracker.save_blacklist_updates(tracker.clone()).await;
}
if tracker_config.keys_enabled {
let _ = tracker.save_key_updates(tracker.clone()).await;
}
if tracker_config.users_enabled {
let _ = tracker.save_user_updates(tracker.clone()).await;
}
} else {
tracker.set_stats(StatsEvent::Completed, config.tracker_config.total_downloads as i64);
Configuration::save_from_config(tracker.config.clone(), "config.toml");
info!("Saving completed data to config...");
}
task::sleep(Duration::from_secs(1)).await;
info!("Server shutting down completed");
mem::forget(tokio_core);
mem::forget(udp_tokio_threads);
Ok(())
}
}
})
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs.rs | src/udp/structs.rs | pub mod connect_request;
pub mod announce_request;
pub mod scrape_request;
pub mod torrent_scrape_statistics;
pub mod connect_response;
pub mod announce_response;
pub mod scrape_response;
pub mod error_response;
pub mod announce_interval;
pub mod connection_id;
pub mod transaction_id;
pub mod number_of_peers;
pub mod number_of_downloads;
pub mod port;
pub mod peer_key;
pub mod response_peer;
pub mod udp_server;
pub mod parse_pool;
pub mod udp_packet;
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/enums.rs | src/udp/enums.rs | pub mod request_parse_error;
pub mod request;
pub mod response;
pub mod server_error; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/udp.rs | src/udp/udp.rs | use std::net::SocketAddr;
use std::process::exit;
use std::sync::Arc;
use log::{error, info};
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::udp::structs::udp_server::UdpServer;
pub const PROTOCOL_IDENTIFIER: i64 = 4_497_486_125_440;
pub const MAX_SCRAPE_TORRENTS: u8 = 74;
pub const MAX_PACKET_SIZE: usize = 1496;
#[allow(clippy::too_many_arguments)]
pub async fn udp_service(addr: SocketAddr, udp_threads: usize, worker_threads: usize, recv_buffer_size: usize, send_buffer_size: usize, reuse_address: bool, data: Arc<TorrentTracker>, rx: tokio::sync::watch::Receiver<bool>, tokio_udp: Arc<Runtime>) -> JoinHandle<()>
{
let udp_server = UdpServer::new(data, addr, udp_threads, worker_threads, recv_buffer_size, send_buffer_size, reuse_address).await.unwrap_or_else(|e| {
error!("Could not listen to the UDP port: {e}");
exit(1);
});
info!("[UDP] Starting a server listener on {addr} with {udp_threads} UDP threads and {worker_threads} worker threads");
tokio_udp.spawn(async move {
udp_server.start(rx).await;
})
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/mod.rs | src/udp/mod.rs | pub mod enums;
pub mod impls;
pub mod structs;
pub mod traits;
#[allow(clippy::module_inception)]
pub mod udp; | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls.rs | src/udp/impls.rs | pub mod request_parse_error;
pub mod request;
pub mod response;
pub mod ipv4_addr;
pub mod ipv6_addr;
pub mod udp_server;
pub mod parse_pool;
| rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/traits.rs | src/udp/traits.rs | use std::fmt::Debug;
pub trait Ip: Clone + Copy + Debug + PartialEq + Eq {} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/ipv4_addr.rs | src/udp/impls/ipv4_addr.rs | use std::net::Ipv4Addr;
use crate::udp::traits::Ip;
impl Ip for Ipv4Addr {} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/response.rs | src/udp/impls/response.rs | use std::convert::TryInto;
use std::io;
use std::io::{Cursor, Write};
use std::net::{Ipv4Addr, Ipv6Addr};
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use crate::udp::enums::response::Response;
use crate::udp::structs::announce_interval::AnnounceInterval;
use crate::udp::structs::announce_response::AnnounceResponse;
use crate::udp::structs::connect_response::ConnectResponse;
use crate::udp::structs::connection_id::ConnectionId;
use crate::udp::structs::error_response::ErrorResponse;
use crate::udp::structs::number_of_downloads::NumberOfDownloads;
use crate::udp::structs::number_of_peers::NumberOfPeers;
use crate::udp::structs::port::Port;
use crate::udp::structs::response_peer::ResponsePeer;
use crate::udp::structs::scrape_response::ScrapeResponse;
use crate::udp::structs::torrent_scrape_statistics::TorrentScrapeStatistics;
use crate::udp::structs::transaction_id::TransactionId;
impl From<ConnectResponse> for Response {
fn from(r: ConnectResponse) -> Self {
Self::Connect(r)
}
}
impl From<AnnounceResponse<Ipv4Addr>> for Response {
fn from(r: AnnounceResponse<Ipv4Addr>) -> Self {
Self::AnnounceIpv4(r)
}
}
impl From<AnnounceResponse<Ipv6Addr>> for Response {
fn from(r: AnnounceResponse<Ipv6Addr>) -> Self {
Self::AnnounceIpv6(r)
}
}
impl From<ScrapeResponse> for Response {
fn from(r: ScrapeResponse) -> Self {
Self::Scrape(r)
}
}
impl From<ErrorResponse> for Response {
fn from(r: ErrorResponse) -> Self {
Self::Error(r)
}
}
impl Response {
#[tracing::instrument(skip(bytes), level = "debug")]
#[inline]
pub fn write(&self, bytes: &mut impl Write) -> Result<(), io::Error> {
match self {
Response::Connect(r) => {
bytes.write_i32::<NetworkEndian>(0)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
bytes.write_i64::<NetworkEndian>(r.connection_id.0)?;
}
Response::AnnounceIpv4(r) => {
bytes.write_i32::<NetworkEndian>(1)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
bytes.write_i32::<NetworkEndian>(r.announce_interval.0)?;
bytes.write_i32::<NetworkEndian>(r.leechers.0)?;
bytes.write_i32::<NetworkEndian>(r.seeders.0)?;
let peer_count = r.peers.len();
if peer_count > 0 {
let mut peer_buffer = Vec::with_capacity(peer_count * 6);
for peer in &r.peers {
peer_buffer.extend_from_slice(&peer.ip_address.octets());
peer_buffer.write_u16::<NetworkEndian>(peer.port.0)?;
}
bytes.write_all(&peer_buffer)?;
}
}
Response::AnnounceIpv6(r) => {
bytes.write_i32::<NetworkEndian>(1)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
bytes.write_i32::<NetworkEndian>(r.announce_interval.0)?;
bytes.write_i32::<NetworkEndian>(r.leechers.0)?;
bytes.write_i32::<NetworkEndian>(r.seeders.0)?;
let peer_count = r.peers.len();
if peer_count > 0 {
let mut peer_buffer = Vec::with_capacity(peer_count * 18);
for peer in &r.peers {
peer_buffer.extend_from_slice(&peer.ip_address.octets());
peer_buffer.write_u16::<NetworkEndian>(peer.port.0)?;
}
bytes.write_all(&peer_buffer)?;
}
}
Response::Scrape(r) => {
bytes.write_i32::<NetworkEndian>(2)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
let stats_count = r.torrent_stats.len();
if stats_count > 0 {
let mut stats_buffer = Vec::with_capacity(stats_count * 12);
for torrent_stat in &r.torrent_stats {
stats_buffer.write_i32::<NetworkEndian>(torrent_stat.seeders.0)?;
stats_buffer.write_i32::<NetworkEndian>(torrent_stat.completed.0)?;
stats_buffer.write_i32::<NetworkEndian>(torrent_stat.leechers.0)?;
}
bytes.write_all(&stats_buffer)?;
}
}
Response::Error(r) => {
bytes.write_i32::<NetworkEndian>(3)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
bytes.write_all(r.message.as_bytes())?;
}
}
Ok(())
}
#[tracing::instrument(level = "debug")]
#[inline]
pub fn from_bytes(bytes: &[u8], ipv4: bool) -> Result<Self, io::Error> {
let mut cursor = Cursor::new(bytes);
let action = cursor.read_i32::<NetworkEndian>()?;
let transaction_id = cursor.read_i32::<NetworkEndian>()?;
match action {
// Connect
0 => {
let connection_id = cursor.read_i64::<NetworkEndian>()?;
Ok(ConnectResponse {
connection_id: ConnectionId(connection_id),
transaction_id: TransactionId(transaction_id),
}
.into())
}
// Announce
1 => {
let announce_interval = cursor.read_i32::<NetworkEndian>()?;
let leechers = cursor.read_i32::<NetworkEndian>()?;
let seeders = cursor.read_i32::<NetworkEndian>()?;
let position = cursor.position() as usize;
let remaining_bytes = &bytes[position..];
if ipv4 {
let peers = parse_ipv4_peers(remaining_bytes)?;
Ok(AnnounceResponse {
transaction_id: TransactionId(transaction_id),
announce_interval: AnnounceInterval(announce_interval),
leechers: NumberOfPeers(leechers),
seeders: NumberOfPeers(seeders),
peers,
}
.into())
} else {
let peers = parse_ipv6_peers(remaining_bytes)?;
Ok(AnnounceResponse {
transaction_id: TransactionId(transaction_id),
announce_interval: AnnounceInterval(announce_interval),
leechers: NumberOfPeers(leechers),
seeders: NumberOfPeers(seeders),
peers,
}
.into())
}
}
// Scrape
2 => {
let position = cursor.position() as usize;
let remaining_bytes = &bytes[position..];
let torrent_stats = parse_scrape_stats(remaining_bytes)?;
Ok(ScrapeResponse {
transaction_id: TransactionId(transaction_id),
torrent_stats,
}
.into())
}
// Error
3 => {
let position = cursor.position() as usize;
let message_bytes = &bytes[position..];
let message = String::from_utf8_lossy(message_bytes).into_owned();
Ok(ErrorResponse {
transaction_id: TransactionId(transaction_id),
message: message.into(),
}
.into())
}
_ => Ok(ErrorResponse {
transaction_id: TransactionId(transaction_id),
message: "Invalid action".into(),
}
.into()),
}
}
#[inline]
pub fn estimated_size(&self) -> usize {
match self {
Response::Connect(_) => 16,
Response::AnnounceIpv4(r) => 20 + (r.peers.len() * 6),
Response::AnnounceIpv6(r) => 20 + (r.peers.len() * 18),
Response::Scrape(r) => 8 + (r.torrent_stats.len() * 12),
Response::Error(r) => 8 + r.message.len(),
}
}
#[inline]
pub fn write_to_vec(&self) -> Result<Vec<u8>, io::Error> {
let estimated_size = self.estimated_size();
let mut buffer = Vec::with_capacity(estimated_size);
self.write(&mut buffer)?;
Ok(buffer)
}
}
#[inline]
fn parse_ipv4_peers(bytes: &[u8]) -> Result<Vec<ResponsePeer<Ipv4Addr>>, io::Error> {
let chunk_size = 6;
let peer_count = bytes.len() / chunk_size;
let mut peers = Vec::with_capacity(peer_count);
for chunk in bytes.chunks_exact(chunk_size) {
let ip_bytes: [u8; 4] = chunk[..4].try_into().map_err(|_|
io::Error::new(io::ErrorKind::InvalidData, "Invalid IPv4 address bytes")
)?;
let port = (&chunk[4..6]).read_u16::<NetworkEndian>().map_err(|e|
io::Error::new(io::ErrorKind::InvalidData, e)
)?;
peers.push(ResponsePeer {
ip_address: Ipv4Addr::from(ip_bytes),
port: Port(port),
});
}
Ok(peers)
}
#[inline]
fn parse_ipv6_peers(bytes: &[u8]) -> Result<Vec<ResponsePeer<Ipv6Addr>>, io::Error> {
let chunk_size = 18;
let peer_count = bytes.len() / chunk_size;
let mut peers = Vec::with_capacity(peer_count);
for chunk in bytes.chunks_exact(chunk_size) {
let ip_bytes: [u8; 16] = chunk[..16].try_into().map_err(|_|
io::Error::new(io::ErrorKind::InvalidData, "Invalid IPv6 address bytes")
)?;
let port = (&chunk[16..18]).read_u16::<NetworkEndian>().map_err(|e|
io::Error::new(io::ErrorKind::InvalidData, e)
)?;
peers.push(ResponsePeer {
ip_address: Ipv6Addr::from(ip_bytes),
port: Port(port),
});
}
Ok(peers)
}
#[inline]
fn parse_scrape_stats(bytes: &[u8]) -> Result<Vec<TorrentScrapeStatistics>, io::Error> {
let chunk_size = 12;
let stats_count = bytes.len() / chunk_size;
let mut stats = Vec::with_capacity(stats_count);
for chunk in bytes.chunks_exact(chunk_size) {
let mut cursor = Cursor::new(chunk);
let seeders = cursor.read_i32::<NetworkEndian>().map_err(|e|
io::Error::new(io::ErrorKind::InvalidData, e)
)?;
let downloads = cursor.read_i32::<NetworkEndian>().map_err(|e|
io::Error::new(io::ErrorKind::InvalidData, e)
)?;
let leechers = cursor.read_i32::<NetworkEndian>().map_err(|e|
io::Error::new(io::ErrorKind::InvalidData, e)
)?;
stats.push(TorrentScrapeStatistics {
seeders: NumberOfPeers(seeders),
completed: NumberOfDownloads(downloads),
leechers: NumberOfPeers(leechers),
});
}
Ok(stats)
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/parse_pool.rs | src/udp/impls/parse_pool.rs | use std::sync::Arc;
use log::info;
use crossbeam::queue::ArrayQueue;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::udp::structs::parse_pool::ParsePool;
use crate::udp::structs::udp_packet::UdpPacket;
use crate::udp::enums::request::Request;
use crate::udp::enums::response::Response;
use crate::udp::enums::server_error::ServerError;
use crate::udp::structs::transaction_id::TransactionId;
use crate::udp::structs::udp_server::UdpServer;
use crate::udp::udp::MAX_SCRAPE_TORRENTS;
use crate::stats::enums::stats_event::StatsEvent;
impl Default for ParsePool {
fn default() -> Self {
Self::new(0)
}
}
impl ParsePool {
pub fn new(capacity: usize) -> ParsePool {
ParsePool { payload: Arc::new(ArrayQueue::new(capacity)) }
}
pub async fn start_thread(&self, threads: usize, tracker: Arc<TorrentTracker>, shutdown_handler: tokio::sync::watch::Receiver<bool>) {
for i in 0..threads {
let payload = self.payload.clone();
let tracker_cloned = tracker.clone();
let mut shutdown_handler = shutdown_handler.clone();
tokio::spawn(async move {
info!("[UDP] Start Parse Pool thread {i}...");
let mut batch: Vec<UdpPacket> = Vec::with_capacity(64);
const BATCH_MAX: usize = 64;
const EMPTY_YIELD_EVERY: usize = 256;
let mut empty_polls = 0usize;
loop {
batch.clear();
while let Some(packet) = payload.pop() {
batch.push(packet);
if batch.len() >= BATCH_MAX {
break;
}
}
if !batch.is_empty() {
Self::process_batch(&batch, tracker_cloned.clone()).await;
empty_polls = 0;
} else {
empty_polls += 1;
if empty_polls % EMPTY_YIELD_EVERY == 0 {
tokio::task::yield_now().await;
}
}
if shutdown_handler.has_changed().unwrap_or(false)
&& shutdown_handler.changed().await.is_ok() {
info!("[UDP] Shutting down the Parse Pool thread {i}...");
return;
}
}
});
}
}
async fn process_batch(packets: &[UdpPacket], tracker: Arc<TorrentTracker>) {
for packet in packets {
let payload = &packet.data[..packet.data_len];
let response = match Request::from_bytes(payload, MAX_SCRAPE_TORRENTS) {
Ok(request) => {
match UdpServer::handle_request(request, packet.remote_addr, tracker.clone()).await {
Ok(resp) => resp,
Err(_e) => {
match packet.remote_addr {
std::net::SocketAddr::V4(_) => { tracker.update_stats(StatsEvent::Udp4InvalidRequest, 1); }
std::net::SocketAddr::V6(_) => { tracker.update_stats(StatsEvent::Udp6InvalidRequest, 1); }
}
Response::from(crate::udp::structs::error_response::ErrorResponse {
transaction_id: TransactionId(0),
message: ServerError::BadRequest.to_string().into(),
})
}
}
}
Err(_) => {
match packet.remote_addr {
std::net::SocketAddr::V4(_) => { tracker.update_stats(StatsEvent::Udp4BadRequest, 1); }
std::net::SocketAddr::V6(_) => { tracker.update_stats(StatsEvent::Udp6BadRequest, 1); }
}
Response::from(crate::udp::structs::error_response::ErrorResponse {
transaction_id: TransactionId(0),
message: ServerError::BadRequest.to_string().into(),
})
}
};
UdpServer::send_response(tracker.clone(), packet.socket.clone(), packet.remote_addr, response).await;
}
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/ipv6_addr.rs | src/udp/impls/ipv6_addr.rs | use std::net::Ipv6Addr;
use crate::udp::traits::Ip;
impl Ip for Ipv6Addr {} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/udp_server.rs | src/udp/impls/udp_server.rs | use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use log::{debug, info};
use socket2::{Socket, Domain, Type, Protocol};
use tokio::net::UdpSocket;
use tokio::runtime::Builder;
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::enums::torrent_peers_type::TorrentPeersType;
use crate::tracker::structs::announce_query_request::AnnounceQueryRequest;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::peer_id::PeerId;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use crate::tracker::structs::user_id::UserId;
use crate::udp::enums::request::Request;
use crate::udp::enums::response::Response;
use crate::udp::enums::server_error::ServerError;
use crate::udp::structs::announce_interval::AnnounceInterval;
use crate::udp::structs::announce_request::AnnounceRequest;
use crate::udp::structs::announce_response::AnnounceResponse;
use crate::udp::structs::connect_request::ConnectRequest;
use crate::udp::structs::connect_response::ConnectResponse;
use crate::udp::structs::connection_id::ConnectionId;
use crate::udp::structs::error_response::ErrorResponse;
use crate::udp::structs::number_of_downloads::NumberOfDownloads;
use crate::udp::structs::number_of_peers::NumberOfPeers;
use crate::udp::structs::parse_pool::ParsePool;
use crate::udp::structs::port::Port;
use crate::udp::structs::response_peer::ResponsePeer;
use crate::udp::structs::scrape_request::ScrapeRequest;
use crate::udp::structs::scrape_response::ScrapeResponse;
use crate::udp::structs::torrent_scrape_statistics::TorrentScrapeStatistics;
use crate::udp::structs::transaction_id::TransactionId;
use crate::udp::structs::udp_packet::UdpPacket;
use crate::udp::structs::udp_server::UdpServer;
use crate::udp::udp::MAX_SCRAPE_TORRENTS;
impl UdpServer {
#[tracing::instrument(level = "debug")]
pub async fn new(tracker: Arc<TorrentTracker>, bind_address: SocketAddr, udp_threads: usize, worker_threads: usize, recv_buffer_size: usize, send_buffer_size: usize, reuse_address: bool) -> tokio::io::Result<UdpServer>
{
let domain = if bind_address.is_ipv4() { Domain::IPV4 } else { Domain::IPV6 };
let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
socket.set_recv_buffer_size(recv_buffer_size).map_err(tokio::io::Error::other)?;
socket.set_send_buffer_size(send_buffer_size).map_err(tokio::io::Error::other)?;
socket.set_reuse_address(reuse_address).map_err(tokio::io::Error::other)?;
socket.bind(&bind_address.into()).map_err(tokio::io::Error::other)?;
socket.set_nonblocking(true).map_err(tokio::io::Error::other)?;
let std_socket: std::net::UdpSocket = socket.into();
let tokio_socket = UdpSocket::from_std(std_socket)?;
Ok(UdpServer {
socket: Arc::new(tokio_socket),
udp_threads,
worker_threads,
tracker,
})
}
#[tracing::instrument(level = "debug")]
pub async fn start(&self, mut rx: tokio::sync::watch::Receiver<bool>) {
let parse_pool = Arc::new(ParsePool::new(10000));
parse_pool.start_thread(self.worker_threads, self.tracker.clone(), rx.clone()).await;
let payload = parse_pool.payload.clone();
let tracker_queue = self.tracker.clone();
let mut rx_queue = rx.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
tokio::select! {
_ = rx_queue.changed() => {
break;
}
_ = interval.tick() => {
let len = payload.len() as i64;
tracker_queue.set_stats(StatsEvent::UdpQueueLen, len);
}
}
}
});
let udp_threads = self.udp_threads;
let socket_clone = self.socket.clone();
let parse_pool_clone = parse_pool.clone();
tokio::task::spawn_blocking(move || {
let tokio_udp = Builder::new_multi_thread()
.thread_name("udp")
.worker_threads(udp_threads)
.enable_all()
.build()
.unwrap();
tokio_udp.block_on(async move {
for _index in 0..udp_threads {
let parse_pool_clone = parse_pool_clone.clone();
let socket_clone = socket_clone.clone();
let mut rx = rx.clone();
tokio::spawn(async move {
let mut data = [0; 1496];
loop {
let udp_sock = socket_clone.local_addr().unwrap();
tokio::select! {
_ = rx.changed() => {
info!("Stopping UDP server: {udp_sock}...");
break;
}
Ok((valid_bytes, remote_addr)) = socket_clone.recv_from(&mut data) => {
if valid_bytes > 0 {
let packet = UdpPacket {
remote_addr,
data,
data_len: valid_bytes,
socket: socket_clone.clone(),
};
if parse_pool_clone.payload.push(packet).is_err() {
debug!("Parse pool queue full, dropping packet");
}
}
}
}
}
});
}
rx.changed().await.ok();
});
});
}
#[tracing::instrument(level = "debug")]
pub async fn send_response(tracker: Arc<TorrentTracker>, socket: Arc<UdpSocket>, remote_addr: SocketAddr, response: Response) {
debug!("sending response to: {:?}", &remote_addr);
let estimated_size = response.estimated_size();
let mut buffer = Vec::with_capacity(estimated_size);
match response.write(&mut buffer) {
Ok(_) => {
UdpServer::send_packet(socket, &remote_addr, &buffer).await;
}
Err(error) => {
match remote_addr {
SocketAddr::V4(_) => { tracker.update_stats(StatsEvent::Udp4InvalidRequest, 1); }
SocketAddr::V6(_) => { tracker.update_stats(StatsEvent::Udp6InvalidRequest, 1); }
}
debug!("could not write response to bytes: {error}");
}
}
}
#[tracing::instrument(level = "debug")]
pub async fn send_packet(socket: Arc<UdpSocket>, remote_addr: &SocketAddr, payload: &[u8]) {
let _ = socket.send_to(payload, remote_addr).await;
}
#[tracing::instrument(level = "debug")]
pub async fn get_connection_id(remote_address: &SocketAddr) -> ConnectionId {
use std::hash::{Hasher, DefaultHasher};
use std::time::Instant;
let mut hasher = DefaultHasher::new();
hasher.write_u64(Instant::now().elapsed().as_nanos() as u64);
hasher.write_u16(remote_address.port());
if let std::net::IpAddr::V4(ipv4) = remote_address.ip() {
hasher.write(&ipv4.octets());
} else if let std::net::IpAddr::V6(ipv6) = remote_address.ip() {
hasher.write(&ipv6.octets());
}
ConnectionId(hasher.finish() as i64)
}
#[tracing::instrument(level = "debug")]
pub async fn handle_packet(remote_addr: SocketAddr, payload: &[u8], tracker: Arc<TorrentTracker>) -> Response {
if payload.len() >= 16
&& payload[8..12] == [0, 0, 0, 0] {
if let Ok(Request::Connect(connect_request)) = Request::from_bytes(payload, MAX_SCRAPE_TORRENTS) {
return match UdpServer::handle_udp_connect(remote_addr, &connect_request, tracker).await {
Ok(response) => response,
Err(e) => UdpServer::handle_udp_error(e, connect_request.transaction_id).await,
};
}
}
let transaction_id = match Request::from_bytes(payload, MAX_SCRAPE_TORRENTS) {
Ok(request) => {
let tid = match &request {
Request::Connect(connect_request) => connect_request.transaction_id,
Request::Announce(announce_request) => announce_request.transaction_id,
Request::Scrape(scrape_request) => scrape_request.transaction_id,
};
match UdpServer::handle_request(request, remote_addr, tracker.clone()).await {
Ok(response) => return response,
Err(_e) => {
match remote_addr {
SocketAddr::V4(_) => { tracker.update_stats(StatsEvent::Udp4InvalidRequest, 1); }
SocketAddr::V6(_) => { tracker.update_stats(StatsEvent::Udp6InvalidRequest, 1); }
}
tid
}
}
}
Err(_) => {
match remote_addr {
SocketAddr::V4(_) => { tracker.update_stats(StatsEvent::Udp4BadRequest, 1); }
SocketAddr::V6(_) => { tracker.update_stats(StatsEvent::Udp6BadRequest, 1); }
}
TransactionId(0)
}
};
UdpServer::handle_udp_error(ServerError::BadRequest, transaction_id).await
}
#[tracing::instrument(level = "debug")]
pub async fn handle_request(request: Request, remote_addr: SocketAddr, tracker: Arc<TorrentTracker>) -> Result<Response, ServerError> {
let sentry = sentry::TransactionContext::new("udp server", "handle packet");
let transaction = sentry::start_transaction(sentry);
let result = match request {
Request::Connect(connect_request) => {
UdpServer::handle_udp_connect(remote_addr, &connect_request, tracker).await
}
Request::Announce(announce_request) => {
UdpServer::handle_udp_announce(remote_addr, &announce_request, tracker).await
}
Request::Scrape(scrape_request) => {
UdpServer::handle_udp_scrape(remote_addr, &scrape_request, tracker).await
}
};
transaction.finish();
result
}
#[tracing::instrument(level = "debug")]
pub async fn handle_udp_connect(remote_addr: SocketAddr, request: &ConnectRequest, tracker: Arc<TorrentTracker>) -> Result<Response, ServerError> {
let connection_id = UdpServer::get_connection_id(&remote_addr).await;
let response = Response::from(ConnectResponse {
transaction_id: request.transaction_id,
connection_id
});
let stats_event = if remote_addr.is_ipv4() {
StatsEvent::Udp4ConnectionsHandled
} else {
StatsEvent::Udp6ConnectionsHandled
};
tracker.update_stats(stats_event, 1);
Ok(response)
}
#[tracing::instrument(level = "debug")]
pub async fn handle_udp_announce(remote_addr: SocketAddr, request: &AnnounceRequest, tracker: Arc<TorrentTracker>) -> Result<Response, ServerError> {
let config = tracker.config.tracker_config.clone();
if config.whitelist_enabled && !tracker.check_whitelist(InfoHash(request.info_hash.0)) {
debug!("[UDP ERROR] Torrent Not Whitelisted");
return Err(ServerError::TorrentNotWhitelisted);
}
if config.blacklist_enabled && tracker.check_blacklist(InfoHash(request.info_hash.0)) {
debug!("[UDP ERROR] Torrent Blacklisted");
return Err(ServerError::TorrentBlacklisted);
}
if config.keys_enabled {
if request.path.len() < 50 {
debug!("[UDP ERROR] Unknown Key");
return Err(ServerError::UnknownKey);
}
let key_path_extract = &request.path[10..50];
if let Ok(result) = hex::decode(key_path_extract) {
if result.len() >= 20 {
let key = <[u8; 20]>::try_from(&result[0..20]).unwrap();
if !tracker.check_key(InfoHash::from(key)) {
debug!("[UDP ERROR] Unknown Key");
return Err(ServerError::UnknownKey);
}
} else {
debug!("[UDP ERROR] Unknown Key - insufficient bytes");
return Err(ServerError::UnknownKey);
}
} else {
debug!("[UDP ERROR] Unknown Key");
return Err(ServerError::UnknownKey);
}
}
let user_key = if config.users_enabled {
let user_key_path_extract = if request.path.len() >= 91 {
Some(&request.path[51..=91])
} else if !config.users_enabled && request.path.len() >= 50 {
Some(&request.path[10..=50])
} else {
None
};
if let Some(path) = user_key_path_extract {
match hex::decode(path) {
Ok(result) if result.len() >= 20 => {
let key = <[u8; 20]>::try_from(&result[0..20]).unwrap();
tracker.check_user_key(UserId::from(key))
}
_ => {
debug!("[UDP ERROR] Peer Key Not Valid");
return Err(ServerError::PeerKeyNotValid);
}
}
} else {
None
}
} else {
None
};
if config.users_enabled && user_key.is_none() {
debug!("[UDP ERROR] Peer Key Not Valid");
return Err(ServerError::PeerKeyNotValid);
}
let torrent = match tracker.handle_announce(tracker.clone(), AnnounceQueryRequest {
info_hash: InfoHash(request.info_hash.0),
peer_id: PeerId(request.peer_id.0),
port: request.port.0,
uploaded: request.bytes_uploaded.0 as u64,
downloaded: request.bytes_downloaded.0 as u64,
left: request.bytes_left.0 as u64,
compact: false,
no_peer_id: false,
event: request.event,
remote_addr: remote_addr.ip(),
numwant: request.peers_wanted.0 as u64,
}, user_key).await {
Ok(result) => result.1,
Err(error) => {
debug!("[UDP ERROR] Handle Announce - Internal Server Error: {error:#?}");
return Err(ServerError::InternalServerError);
}
};
let torrent_peers = tracker.get_torrent_peers(request.info_hash, 72, TorrentPeersType::All, Some(remote_addr.ip()));
let (peers, peers6) = if let Some(torrent_peers_unwrapped) = torrent_peers {
let mut peers = Vec::with_capacity(72);
let mut peers6 = Vec::with_capacity(72);
let mut count = 0;
if request.bytes_left.0 != 0 {
if remote_addr.is_ipv4() {
for torrent_peer in torrent_peers_unwrapped.seeds_ipv4.values().take(72) {
if count >= 72 { break; }
if let Ok(ip) = torrent_peer.peer_addr.ip().to_string().parse::<Ipv4Addr>() {
peers.push(ResponsePeer { ip_address: ip, port: Port(torrent_peer.peer_addr.port()) });
count += 1;
}
}
} else {
for torrent_peer in torrent_peers_unwrapped.seeds_ipv6.values().take(72) {
if count >= 72 { break; }
if let Ok(ip) = torrent_peer.peer_addr.ip().to_string().parse::<Ipv6Addr>() {
peers6.push(ResponsePeer { ip_address: ip, port: Port(torrent_peer.peer_addr.port()) });
count += 1;
}
}
}
}
if remote_addr.is_ipv4() {
for torrent_peer in torrent_peers_unwrapped.peers_ipv4.values().take(72 - count) {
if let std::net::IpAddr::V4(ip) = torrent_peer.peer_addr.ip() {
peers.push(ResponsePeer { ip_address: ip, port: Port(torrent_peer.peer_addr.port()) });
}
}
} else {
for torrent_peer in torrent_peers_unwrapped.peers_ipv6.values().take(72 - count) {
if let std::net::IpAddr::V6(ip) = torrent_peer.peer_addr.ip() {
peers6.push(ResponsePeer { ip_address: ip, port: Port(torrent_peer.peer_addr.port()) });
}
}
}
(peers, peers6)
} else {
(Vec::new(), Vec::new())
};
let response = if remote_addr.is_ipv6() {
Response::from(AnnounceResponse {
transaction_id: request.transaction_id,
announce_interval: AnnounceInterval(config.request_interval as i32),
leechers: NumberOfPeers(torrent.peers.len() as i32),
seeders: NumberOfPeers(torrent.seeds.len() as i32),
peers: peers6,
})
} else {
Response::from(AnnounceResponse {
transaction_id: request.transaction_id,
announce_interval: AnnounceInterval(config.request_interval as i32),
leechers: NumberOfPeers(torrent.peers.len() as i32),
seeders: NumberOfPeers(torrent.seeds.len() as i32),
peers,
})
};
let stats_event = if remote_addr.is_ipv4() {
StatsEvent::Udp4AnnouncesHandled
} else {
StatsEvent::Udp6AnnouncesHandled
};
tracker.update_stats(stats_event, 1);
Ok(response)
}
#[tracing::instrument(level = "debug")]
pub async fn handle_udp_scrape(remote_addr: SocketAddr, request: &ScrapeRequest, tracker: Arc<TorrentTracker>) -> Result<Response, ServerError> {
let mut torrent_stats = Vec::with_capacity(request.info_hashes.len());
for info_hash in &request.info_hashes {
let scrape_entry = match tracker.get_torrent(InfoHash(info_hash.0)) {
Some(torrent_info) => TorrentScrapeStatistics {
seeders: NumberOfPeers(torrent_info.seeds.len() as i32),
completed: NumberOfDownloads(torrent_info.completed as i32),
leechers: NumberOfPeers(torrent_info.peers.len() as i32),
},
None => TorrentScrapeStatistics {
seeders: NumberOfPeers(0),
completed: NumberOfDownloads(0),
leechers: NumberOfPeers(0),
},
};
torrent_stats.push(scrape_entry);
}
let stats_event = if remote_addr.is_ipv4() {
StatsEvent::Udp4ScrapesHandled
} else {
StatsEvent::Udp6ScrapesHandled
};
tracker.update_stats(stats_event, 1);
Ok(Response::from(ScrapeResponse {
transaction_id: request.transaction_id,
torrent_stats,
}))
}
#[tracing::instrument(level = "debug")]
pub async fn handle_udp_error(e: ServerError, transaction_id: TransactionId) -> Response {
Response::from(ErrorResponse {
transaction_id,
message: e.to_string().into()
})
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/request.rs | src/udp/impls/request.rs | use std::io;
use std::io::{Cursor, Read, Write};
use std::net::Ipv4Addr;
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use crate::common::structs::number_of_bytes::NumberOfBytes;
use crate::tracker::enums::announce_event::AnnounceEvent;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::peer_id::PeerId;
use crate::udp::enums::request::Request;
use crate::udp::enums::request_parse_error::RequestParseError;
use crate::udp::structs::announce_request::AnnounceRequest;
use crate::udp::structs::connect_request::ConnectRequest;
use crate::udp::structs::connection_id::ConnectionId;
use crate::udp::structs::number_of_peers::NumberOfPeers;
use crate::udp::structs::peer_key::PeerKey;
use crate::udp::structs::port::Port;
use crate::udp::structs::scrape_request::ScrapeRequest;
use crate::udp::structs::transaction_id::TransactionId;
use crate::udp::udp::PROTOCOL_IDENTIFIER;
impl From<ConnectRequest> for Request {
fn from(r: ConnectRequest) -> Self {
Self::Connect(r)
}
}
impl From<AnnounceRequest> for Request {
fn from(r: AnnounceRequest) -> Self {
Self::Announce(r)
}
}
impl From<ScrapeRequest> for Request {
fn from(r: ScrapeRequest) -> Self {
Self::Scrape(r)
}
}
impl Request {
#[tracing::instrument(skip(bytes), level = "debug")]
pub fn write(self, bytes: &mut impl Write) -> Result<(), io::Error> {
match self {
Request::Connect(r) => {
bytes.write_i64::<NetworkEndian>(PROTOCOL_IDENTIFIER)?;
bytes.write_i32::<NetworkEndian>(0)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
}
Request::Announce(r) => {
bytes.write_i64::<NetworkEndian>(r.connection_id.0)?;
bytes.write_i32::<NetworkEndian>(1)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
bytes.write_all(&r.info_hash.0)?;
bytes.write_all(&r.peer_id.0)?;
bytes.write_i64::<NetworkEndian>(r.bytes_downloaded.0)?;
bytes.write_i64::<NetworkEndian>(r.bytes_left.0)?;
bytes.write_i64::<NetworkEndian>(r.bytes_uploaded.0)?;
bytes.write_i32::<NetworkEndian>(r.event.to_i32())?;
bytes.write_all(&r.ip_address.map_or([0; 4], |ip| ip.octets()))?;
bytes.write_u32::<NetworkEndian>(r.key.0)?;
bytes.write_i32::<NetworkEndian>(r.peers_wanted.0)?;
bytes.write_u16::<NetworkEndian>(r.port.0)?;
}
Request::Scrape(r) => {
bytes.write_i64::<NetworkEndian>(r.connection_id.0)?;
bytes.write_i32::<NetworkEndian>(2)?;
bytes.write_i32::<NetworkEndian>(r.transaction_id.0)?;
for info_hash in r.info_hashes {
bytes.write_all(&info_hash.0)?;
}
}
}
Ok(())
}
#[tracing::instrument(level = "debug")]
pub fn from_bytes(bytes: &[u8], max_scrape_torrents: u8) -> Result<Self, RequestParseError> {
if bytes.len() < 16 {
return Err(RequestParseError::unsendable_text("Packet too short"));
}
let connection_id = i64::from_be_bytes(bytes[0..8].try_into().map_err(|_|
RequestParseError::unsendable_io(io::Error::new(io::ErrorKind::InvalidData, "Invalid connection_id"))
)?);
let action = i32::from_be_bytes(bytes[8..12].try_into().map_err(|_|
RequestParseError::unsendable_io(io::Error::new(io::ErrorKind::InvalidData, "Invalid action"))
)?);
let transaction_id = i32::from_be_bytes(bytes[12..16].try_into().map_err(|_|
RequestParseError::unsendable_io(io::Error::new(io::ErrorKind::InvalidData, "Invalid transaction_id"))
)?);
if action == 0 {
if connection_id == PROTOCOL_IDENTIFIER {
return Ok(ConnectRequest {
transaction_id: TransactionId(transaction_id),
}.into());
} else {
return Err(RequestParseError::unsendable_text("Protocol identifier missing"));
}
}
let mut cursor = Cursor::new(bytes);
cursor.set_position(16);
match action {
// Connect
0 => {
if connection_id == PROTOCOL_IDENTIFIER {
Ok(ConnectRequest {
transaction_id: TransactionId(transaction_id),
}.into())
} else {
Err(RequestParseError::unsendable_text(
"Protocol identifier missing",
))
}
}
// Announce
1 => {
let mut info_hash = [0; 20];
let mut peer_id = [0; 20];
let mut ip = [0; 4];
let sendable_err = |err: io::Error| {
RequestParseError::sendable_io(err, connection_id, transaction_id)
};
cursor.read_exact(&mut info_hash).map_err(sendable_err)?;
cursor.read_exact(&mut peer_id).map_err(sendable_err)?;
let bytes_downloaded = cursor.read_i64::<NetworkEndian>().map_err(sendable_err)?;
let bytes_left = cursor.read_i64::<NetworkEndian>().map_err(sendable_err)?;
let bytes_uploaded = cursor.read_i64::<NetworkEndian>().map_err(sendable_err)?;
let event = cursor.read_i32::<NetworkEndian>().map_err(sendable_err)?;
cursor.read_exact(&mut ip).map_err(sendable_err)?;
let key = cursor.read_u32::<NetworkEndian>().map_err(sendable_err)?;
let peers_wanted = cursor.read_i32::<NetworkEndian>().map_err(sendable_err)?;
let port = cursor.read_u16::<NetworkEndian>().map_err(sendable_err)?;
let opt_ip = if ip == [0; 4] {
None
} else {
Some(Ipv4Addr::from(ip))
};
let path = if cursor.position() < bytes.len() as u64 {
let option_byte = cursor.read_u8().ok();
let option_size = cursor.read_u8().ok();
if option_byte == Some(2) {
if let Some(size) = option_size {
let size_usize = size as usize;
if cursor.position() + size_usize as u64 <= bytes.len() as u64 {
let start_pos = cursor.position() as usize;
let end_pos = start_pos + size_usize;
std::str::from_utf8(&bytes[start_pos..end_pos])
.unwrap_or_default()
.to_string()
} else {
String::new()
}
} else {
String::new()
}
} else {
String::new()
}
} else {
String::new()
};
Ok(AnnounceRequest {
connection_id: ConnectionId(connection_id),
transaction_id: TransactionId(transaction_id),
info_hash: InfoHash(info_hash),
peer_id: PeerId(peer_id),
bytes_downloaded: NumberOfBytes(bytes_downloaded),
bytes_uploaded: NumberOfBytes(bytes_uploaded),
bytes_left: NumberOfBytes(bytes_left),
event: AnnounceEvent::from_i32(event),
ip_address: opt_ip,
key: PeerKey(key),
peers_wanted: NumberOfPeers(peers_wanted),
port: Port(port),
path,
}.into())
}
// Scrape
2 => {
let position = cursor.position() as usize;
let remaining_bytes = &bytes[position..];
let max_hashes = max_scrape_torrents as usize;
let available_hashes = remaining_bytes.len() / 20;
let actual_hashes = available_hashes.min(max_hashes);
if actual_hashes == 0 {
return Err(RequestParseError::sendable_text(
"Full scrapes are not allowed",
connection_id,
transaction_id,
));
}
let mut info_hashes = Vec::with_capacity(actual_hashes);
for chunk in remaining_bytes.chunks_exact(20).take(actual_hashes) {
let hash_array: [u8; 20] = chunk.try_into()
.map_err(|_| RequestParseError::sendable_text(
"Invalid info hash format",
connection_id,
transaction_id,
))?;
info_hashes.push(InfoHash(hash_array));
}
Ok(ScrapeRequest {
connection_id: ConnectionId(connection_id),
transaction_id: TransactionId(transaction_id),
info_hashes,
}.into())
}
_ => Err(RequestParseError::sendable_text(
"Invalid action",
connection_id,
transaction_id,
)),
}
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/impls/request_parse_error.rs | src/udp/impls/request_parse_error.rs | use std::io;
use std::borrow::Cow;
use crate::udp::enums::request_parse_error::RequestParseError;
use crate::udp::structs::connection_id::ConnectionId;
use crate::udp::structs::transaction_id::TransactionId;
impl RequestParseError {
#[tracing::instrument(level = "debug")]
pub fn sendable_io(err: io::Error, connection_id: i64, transaction_id: i32) -> Self {
Self::Sendable {
connection_id: ConnectionId(connection_id),
transaction_id: TransactionId(transaction_id),
err: Cow::Owned(err.to_string()),
}
}
#[tracing::instrument(level = "debug")]
pub fn sendable_text(text: &'static str, connection_id: i64, transaction_id: i32) -> Self {
Self::Sendable {
connection_id: ConnectionId(connection_id),
transaction_id: TransactionId(transaction_id),
err: Cow::Borrowed(text),
}
}
#[tracing::instrument(level = "debug")]
pub fn unsendable_io(err: io::Error) -> Self {
Self::Unsendable {
err: Cow::Owned(err.to_string()),
}
}
#[tracing::instrument(level = "debug")]
pub fn unsendable_text(text: &'static str) -> Self {
Self::Unsendable {
err: Cow::Borrowed(text),
}
}
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs/scrape_response.rs | src/udp/structs/scrape_response.rs | use crate::udp::structs::torrent_scrape_statistics::TorrentScrapeStatistics;
use crate::udp::structs::transaction_id::TransactionId;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ScrapeResponse {
pub transaction_id: TransactionId,
pub torrent_stats: Vec<TorrentScrapeStatistics>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs/torrent_scrape_statistics.rs | src/udp/structs/torrent_scrape_statistics.rs | use crate::udp::structs::number_of_downloads::NumberOfDownloads;
use crate::udp::structs::number_of_peers::NumberOfPeers;
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub struct TorrentScrapeStatistics {
pub seeders: NumberOfPeers,
pub completed: NumberOfDownloads,
pub leechers: NumberOfPeers,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs/parse_pool.rs | src/udp/structs/parse_pool.rs | use std::sync::Arc;
use crate::udp::structs::udp_packet::UdpPacket;
use crossbeam::queue::ArrayQueue;
pub struct ParsePool {
pub payload: Arc<ArrayQueue<UdpPacket>>
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs/udp_packet.rs | src/udp/structs/udp_packet.rs | use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::UdpSocket;
use crate::udp::udp::MAX_PACKET_SIZE;
#[derive(Debug, Clone)]
pub struct UdpPacket {
pub remote_addr: SocketAddr,
pub data: [u8; MAX_PACKET_SIZE],
pub data_len: usize,
pub socket: Arc<UdpSocket>,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Power2All/torrust-actix | https://github.com/Power2All/torrust-actix/blob/20d91c8be4b979abd1d67602b898a444d48a8945/src/udp/structs/announce_request.rs | src/udp/structs/announce_request.rs | use std::net::Ipv4Addr;
use crate::common::structs::number_of_bytes::NumberOfBytes;
use crate::tracker::enums::announce_event::AnnounceEvent;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::peer_id::PeerId;
use crate::udp::structs::connection_id::ConnectionId;
use crate::udp::structs::number_of_peers::NumberOfPeers;
use crate::udp::structs::peer_key::PeerKey;
use crate::udp::structs::port::Port;
use crate::udp::structs::transaction_id::TransactionId;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct AnnounceRequest {
pub connection_id: ConnectionId,
pub transaction_id: TransactionId,
pub info_hash: InfoHash,
pub peer_id: PeerId,
pub bytes_downloaded: NumberOfBytes,
pub bytes_uploaded: NumberOfBytes,
pub bytes_left: NumberOfBytes,
pub event: AnnounceEvent,
pub ip_address: Option<Ipv4Addr>,
pub key: PeerKey,
pub peers_wanted: NumberOfPeers,
pub port: Port,
pub path: String,
} | rust | MIT | 20d91c8be4b979abd1d67602b898a444d48a8945 | 2026-01-04T20:24:47.160557Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.