Truly independent web browser
LibJS+LibUnicode: Use the Rust calendars without a C++ round trip
Andreas Kling9f480604f0cd
diff --git a/Libraries/LibJS/Rust/src/unicode/calendar.rs b/Libraries/LibJS/Rust/src/unicode/calendar.rsindex 4d2a8320ae9..2676b0edda3 100644--- a/Libraries/LibJS/Rust/src/unicode/calendar.rs+++ b/Libraries/LibJS/Rust/src/unicode/calendar.rs@@ -4,99 +4,15 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The calendars of LibUnicode/Calendar.h, through the C exports of LibUnicode/TextMapping.h, so that Temporal-//! converts between ISO dates and calendar dates with the same ICU data as the rest of Ladybird.+//! The calendars of LibUnicode, through its Rust crate, so that Temporal converts between ISO dates and calendar dates+//! with the same ICU data as the rest of Ladybird.use ak::Utf16String;+use libunicode_rust::calendar as icu;+use libunicode_rust::calendar::FfiISODate;-use super::{UnicodeTextMappingOutput, collect_text};use crate::utf16::Utf16View;-#[repr(C)]-#[derive(Clone, Copy, Default)]-struct UnicodeISODate {- year: i32,- month: u8,- day: u8,-}--#[repr(C)]-#[derive(Default)]-struct UnicodeCalendarDate {- has_era: bool,- has_era_year: bool,- era_year: i32,- year: i32,- month: u8,- day: u8,- day_of_week: u8,- day_of_year: u16,- has_week_of_year: bool,- week_of_year: u8,- has_year_of_week: bool,- year_of_week: i32,- days_in_week: u8,- days_in_month: u8,- days_in_year: u16,- months_in_year: u8,- in_leap_year: bool,-}--unsafe extern "C" {- fn unicode_parse_month_code(- month_code: *const u16,- length: usize,- month_number: *mut u8,- is_leap_month: *mut bool,- ) -> bool;- fn unicode_create_month_code(month_number: u8, is_leap_month: bool, output: UnicodeTextMappingOutput);- fn unicode_iso_date_to_calendar_date(- calendar: *const u8,- calendar_length: usize,- iso_date: UnicodeISODate,- calendar_date: *mut UnicodeCalendarDate,- era: UnicodeTextMappingOutput,- month_code: UnicodeTextMappingOutput,- );- fn unicode_calendar_date_to_iso_date(- calendar: *const u8,- calendar_length: usize,- year: i32,- month: u8,- day: u8,- iso_date: *mut UnicodeISODate,- ) -> bool;- fn unicode_iso_year_and_month_code_to_iso_date(- calendar: *const u8,- calendar_length: usize,- year: i32,- month_code: *const u16,- month_code_length: usize,- day: u8,- iso_date: *mut UnicodeISODate,- ) -> bool;- fn unicode_calendar_months_in_year(calendar: *const u8, calendar_length: usize, arithmetic_year: i32) -> u8;- fn unicode_calendar_days_in_month(- calendar: *const u8,- calendar_length: usize,- arithmetic_year: i32,- ordinal_month: u8,- ) -> u8;- fn unicode_calendar_max_days_in_month_code(- calendar: *const u8,- calendar_length: usize,- month_code: *const u16,- month_code_length: usize,- ) -> u8;- fn unicode_calendar_year_contains_month_code(- calendar: *const u8,- calendar_length: usize,- arithmetic_year: i32,- month_code: *const u16,- month_code_length: usize,- ) -> bool;-}-/// Unicode::ISODate, 3.5.1 ISO Date Records, https://tc39.es/proposal-temporal/#sec-temporal-iso-date-records#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub struct ISODate {@@ -105,8 +21,8 @@ pub struct ISODate {pub day: u8,}-impl From<UnicodeISODate> for ISODate {- fn from(iso_date: UnicodeISODate) -> Self {+impl From<FfiISODate> for ISODate {+ fn from(iso_date: FfiISODate) -> Self {ISODate {year: iso_date.year,month: iso_date.month,@@ -149,74 +65,118 @@ pub struct CalendarDate {pub in_leap_year: bool,}-fn code_units_of(text: Utf16View<'_>) -> Vec<u16> {- text.code_units().collect()+/// A month code as the ASCII string the calendars take. Month codes are validated before they get here, as+/// LibUnicode's month_code_as_ascii_bytes() requires.+fn month_code_as_ascii(month_code: Utf16View<'_>) -> String {+ let month_code: String = month_code+ .code_units()+ .map(|code_unit| {+ assert!(code_unit < 0x80, "month codes are ASCII");+ char::from(code_unit as u8)+ })+ .collect();+ assert!(month_code.len() <= 4, "month codes are at most four characters");+ month_code+}++fn is_valid_month_code_string(month_code: &[u16]) -> bool {+ // MonthCode :::+ // M00L+ // M0 NonZeroDigit L[opt]+ // M NonZeroDigit DecimalDigit L[opt]+ let is_ascii_digit = |code_unit: u16| (u16::from(b'0')..=u16::from(b'9')).contains(&code_unit);+ let length = month_code.len();++ if length != 3 && length != 4 {+ return false;+ }++ if month_code[0] != u16::from(b'M') {+ return false;+ }++ if !is_ascii_digit(month_code[1]) || !is_ascii_digit(month_code[2]) {+ return false;+ }++ if length == 3 && month_code[1] == u16::from(b'0') && month_code[2] == u16::from(b'0') {+ return false;+ }+ if length == 4 && month_code[3] != u16::from(b'L') {+ return false;+ }++ true}-/// Unicode::parse_month_code: the month number and leap flag of a month code, or None if it is not a month code.+/// 12.2.1 ParseMonthCode ( argument ), https://tc39.es/proposal-temporal/#sec-temporal-parsemonthcodepub fn parse_month_code(month_code: Utf16View<'_>) -> Option<MonthCode> {- let code_units = code_units_of(month_code);- let mut month_number = 0;+ let month_code: Vec<u16> = month_code.code_units().collect();++ // 3. If ParseText(StringToCodePoints(monthCode), MonthCode) is a List of errors, throw a RangeError exception.+ if !is_valid_month_code_string(&month_code) {+ return None;+ }++ // 4. Let isLeapMonth be false.let mut is_leap_month = false;- // SAFETY: The month code is valid for its length, and the outputs are locals.- let parsed = unsafe {- unicode_parse_month_code(- code_units.as_ptr(),- code_units.len(),- &raw mut month_number,- &raw mut is_leap_month,- )- };- parsed.then_some(MonthCode {++ // 5. If the length of monthCode = 4, then+ if month_code.len() == 4 {+ // a. Assert: The fourth code unit of monthCode is 0x004C (LATIN CAPITAL LETTER L).+ assert_eq!(month_code[3], u16::from(b'L'));++ // b. Set isLeapMonth to true.+ is_leap_month = true;+ }++ // 6. Let monthCodeDigits be the substring of monthCode from 1 to 3.++ // 7. Let monthNumber be ℝ(StringToNumber(monthCodeDigits)).+ let month_number = ((month_code[1] - u16::from(b'0')) * 10 + (month_code[2] - u16::from(b'0'))) as u8;++ // 8. Return the Record { [[MonthNumber]]: monthNumber, [[IsLeapMonth]]: isLeapMonth }.+ Some(MonthCode {month_number,is_leap_month,})}-/// Unicode::create_month_code.+/// 12.2.2 CreateMonthCode ( monthNumber, isLeapMonth ), https://tc39.es/proposal-temporal/#sec-temporal-createmonthcodepub fn create_month_code(month_number: u8, is_leap_month: bool) -> Utf16String {- // SAFETY: The output writes into a Vec.- let ((), month_code) =- collect_text(|output| unsafe { unicode_create_month_code(month_number, is_leap_month, output) });- Utf16String::from_utf16(&month_code)+ // 1. Assert: If isLeapMonth is false, monthNumber > 0.+ if !is_leap_month {+ assert!(month_number > 0);+ }++ // 2. Let numberPart be ToZeroPaddedDecimalString(monthNumber, 2).+ let number_part = format!("{month_number:02}");++ // 3. If isLeapMonth is true, then+ if is_leap_month {+ // a. Return the string-concatenation of the code unit 0x004D (LATIN CAPITAL LETTER M), numberPart, and the+ // code unit 0x004C (LATIN CAPITAL LETTER L).+ return Utf16String::from_ascii(format!("M{number_part}L").as_bytes());+ }++ // 4. Return the string-concatenation of the code unit 0x004D (LATIN CAPITAL LETTER M) and numberPart.+ Utf16String::from_ascii(format!("M{number_part}").as_bytes())}/// Unicode::iso_date_to_calendar_date.pub fn iso_date_to_calendar_date(calendar: &str, iso_date: ISODate) -> CalendarDate {- let mut result = UnicodeCalendarDate::default();- let (month_code, era) = collect_text(|era_output| {- let ((), month_code) = collect_text(|month_code_output| {- // SAFETY: The calendar is valid for its length, the date is a local, and the outputs write into Vecs.- unsafe {- unicode_iso_date_to_calendar_date(- calendar.as_ptr(),- calendar.len(),- UnicodeISODate {- year: iso_date.year,- month: iso_date.month,- day: iso_date.day,- },- &raw mut result,- era_output,- month_code_output,- );- }- });- month_code- });+ let result = icu::iso_date_to_calendar_date(calendar, iso_date.year, iso_date.month, iso_date.day);+ let month_code = &result.month_code[..result.month_code_length as usize];CalendarDate {- era: result.has_era.then(|| Utf16String::from_utf16(&era)),- era_year: result.has_era_year.then_some(result.era_year),+ era: None,+ era_year: None,year: result.year,month: result.month,- month_code: Utf16String::from_utf16(&month_code),+ month_code: Utf16String::from_ascii(month_code),day: result.day,day_of_week: result.day_of_week,day_of_year: result.day_of_year,- week_of_year: YearWeek {- week: result.has_week_of_year.then_some(result.week_of_year),- year: result.has_year_of_week.then_some(result.year_of_week),- },+ week_of_year: YearWeek::default(),days_in_week: result.days_in_week,days_in_month: result.days_in_month,days_in_year: result.days_in_year,@@ -227,12 +187,7 @@ pub fn iso_date_to_calendar_date(calendar: &str, iso_date: ISODate) -> CalendarD/// Unicode::calendar_date_to_iso_date.pub fn calendar_date_to_iso_date(calendar: &str, year: i32, month: u8, day: u8) -> Option<ISODate> {- let mut iso_date = UnicodeISODate::default();- // SAFETY: The calendar is valid for its length, and the output is a local.- let converted = unsafe {- unicode_calendar_date_to_iso_date(calendar.as_ptr(), calendar.len(), year, month, day, &raw mut iso_date)- };- converted.then(|| iso_date.into())+ icu::calendar_date_to_iso_date(calendar, year, month, day).map(ISODate::from)}/// Unicode::iso_year_and_month_code_to_iso_date.@@ -242,60 +197,25 @@ pub fn iso_year_and_month_code_to_iso_date(month_code: Utf16View<'_>,day: u8,) -> Option<ISODate> {- let month_code = code_units_of(month_code);- let mut iso_date = UnicodeISODate::default();- // SAFETY: The calendar and month code are valid for their lengths, and the output is a local.- let converted = unsafe {- unicode_iso_year_and_month_code_to_iso_date(- calendar.as_ptr(),- calendar.len(),- year,- month_code.as_ptr(),- month_code.len(),- day,- &raw mut iso_date,- )- };- converted.then(|| iso_date.into())+ icu::iso_year_and_month_code_to_iso_date(calendar, &month_code_as_ascii(month_code), year, day).map(ISODate::from)}/// Unicode::calendar_months_in_year.pub fn calendar_months_in_year(calendar: &str, arithmetic_year: i32) -> u8 {- // SAFETY: The calendar is valid for its length.- unsafe { unicode_calendar_months_in_year(calendar.as_ptr(), calendar.len(), arithmetic_year) }+ icu::calendar_months_in_year(calendar, arithmetic_year)}/// Unicode::calendar_days_in_month.pub fn calendar_days_in_month(calendar: &str, arithmetic_year: i32, ordinal_month: u8) -> u8 {- // SAFETY: The calendar is valid for its length.- unsafe { unicode_calendar_days_in_month(calendar.as_ptr(), calendar.len(), arithmetic_year, ordinal_month) }+ icu::calendar_days_in_month(calendar, arithmetic_year, ordinal_month)}/// Unicode::calendar_max_days_in_month_code.pub fn calendar_max_days_in_month_code(calendar: &str, month_code: Utf16View<'_>) -> u8 {- let month_code = code_units_of(month_code);- // SAFETY: The calendar and month code are valid for their lengths.- unsafe {- unicode_calendar_max_days_in_month_code(- calendar.as_ptr(),- calendar.len(),- month_code.as_ptr(),- month_code.len(),- )- }+ icu::calendar_max_days_in_month_code(calendar, &month_code_as_ascii(month_code))}/// Unicode::calendar_year_contains_month_code.pub fn calendar_year_contains_month_code(calendar: &str, arithmetic_year: i32, month_code: Utf16View<'_>) -> bool {- let month_code = code_units_of(month_code);- // SAFETY: The calendar and month code are valid for their lengths.- unsafe {- unicode_calendar_year_contains_month_code(- calendar.as_ptr(),- calendar.len(),- arithmetic_year,- month_code.as_ptr(),- month_code.len(),- )- }+ icu::year_contains_month_code(calendar, arithmetic_year, &month_code_as_ascii(month_code))}diff --git a/Libraries/LibUnicode/Calendar.cpp b/Libraries/LibUnicode/Calendar.cppindex 78c801d5167..37be99f6158 100644--- a/Libraries/LibUnicode/Calendar.cpp+++ b/Libraries/LibUnicode/Calendar.cpp@@ -6,7 +6,6 @@#include <LibUnicode/Calendar.h>#include <LibUnicode/RustFFI.h>-#include <LibUnicode/TextMapping.h>namespace Unicode {@@ -176,96 +175,3 @@ bool calendar_year_contains_month_code(StringView calendar, i32 arithmetic_year,}}--static void write_utf16_to(UnicodeTextMappingOutput output, Utf16View text)-{- auto* destination = output.allocate_text(output.context, text.length_in_code_units());- for (size_t i = 0; i < text.length_in_code_units(); ++i)- destination[i] = text.code_unit_at(i);-}--static bool write_iso_date_to(Optional<Unicode::ISODate> const& date, UnicodeISODate* iso_date)-{- if (!date.has_value())- return false;- *iso_date = { date->year, date->month, date->day };- return true;-}--extern "C" bool unicode_parse_month_code(u16 const* month_code, size_t length, u8* month_number, bool* is_leap_month)-{- auto parsed = Unicode::parse_month_code(Utf16View { reinterpret_cast<char16_t const*>(month_code), length });- if (!parsed.has_value())- return false;- *month_number = parsed->month_number;- *is_leap_month = parsed->is_leap_month;- return true;-}--extern "C" void unicode_create_month_code(u8 month_number, bool is_leap_month, UnicodeTextMappingOutput output)-{- auto month_code = Unicode::create_month_code(month_number, is_leap_month);- write_utf16_to(output, month_code.utf16_view());-}--extern "C" void unicode_iso_date_to_calendar_date(u8 const* calendar, size_t calendar_length, UnicodeISODate iso_date, UnicodeCalendarDate* calendar_date, UnicodeTextMappingOutput era, UnicodeTextMappingOutput month_code)-{- auto date = Unicode::iso_date_to_calendar_date(StringView { calendar, calendar_length }, { iso_date.year, iso_date.month, iso_date.day });- *calendar_date = {- .has_era = date.era.has_value(),- .has_era_year = date.era_year.has_value(),- .era_year = date.era_year.value_or(0),- .year = date.year,- .month = date.month,- .day = date.day,- .day_of_week = date.day_of_week,- .day_of_year = date.day_of_year,- .has_week_of_year = date.week_of_year.week.has_value(),- .week_of_year = date.week_of_year.week.value_or(0),- .has_year_of_week = date.week_of_year.year.has_value(),- .year_of_week = date.week_of_year.year.value_or(0),- .days_in_week = date.days_in_week,- .days_in_month = date.days_in_month,- .days_in_year = date.days_in_year,- .months_in_year = date.months_in_year,- .in_leap_year = date.in_leap_year,- };- if (date.era.has_value())- write_utf16_to(era, date.era->utf16_view());- write_utf16_to(month_code, date.month_code.utf16_view());-}--extern "C" bool unicode_calendar_date_to_iso_date(u8 const* calendar, size_t calendar_length, i32 year, u8 month, u8 day, UnicodeISODate* iso_date)-{- return write_iso_date_to(Unicode::calendar_date_to_iso_date(StringView { calendar, calendar_length }, year, month, day), iso_date);-}--extern "C" bool unicode_iso_year_and_month_code_to_iso_date(u8 const* calendar, size_t calendar_length, i32 year, u16 const* month_code, size_t month_code_length, u8 day, UnicodeISODate* iso_date)-{- return write_iso_date_to(Unicode::iso_year_and_month_code_to_iso_date(StringView { calendar, calendar_length }, year, Utf16View { reinterpret_cast<char16_t const*>(month_code), month_code_length }, day), iso_date);-}--extern "C" bool unicode_calendar_year_and_month_code_to_iso_date(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u16 const* month_code, size_t month_code_length, u8 day, UnicodeISODate* iso_date)-{- return write_iso_date_to(Unicode::calendar_year_and_month_code_to_iso_date(StringView { calendar, calendar_length }, arithmetic_year, Utf16View { reinterpret_cast<char16_t const*>(month_code), month_code_length }, day), iso_date);-}--extern "C" u8 unicode_calendar_months_in_year(u8 const* calendar, size_t calendar_length, i32 arithmetic_year)-{- return Unicode::calendar_months_in_year(StringView { calendar, calendar_length }, arithmetic_year);-}--extern "C" u8 unicode_calendar_days_in_month(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u8 ordinal_month)-{- return Unicode::calendar_days_in_month(StringView { calendar, calendar_length }, arithmetic_year, ordinal_month);-}--extern "C" u8 unicode_calendar_max_days_in_month_code(u8 const* calendar, size_t calendar_length, u16 const* month_code, size_t month_code_length)-{- return Unicode::calendar_max_days_in_month_code(StringView { calendar, calendar_length }, Utf16View { reinterpret_cast<char16_t const*>(month_code), month_code_length });-}--extern "C" bool unicode_calendar_year_contains_month_code(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u16 const* month_code, size_t month_code_length)-{- return Unicode::calendar_year_contains_month_code(StringView { calendar, calendar_length }, arithmetic_year, Utf16View { reinterpret_cast<char16_t const*>(month_code), month_code_length });-}diff --git a/Libraries/LibUnicode/TextMapping.h b/Libraries/LibUnicode/TextMapping.hindex 27ea09bf53d..59560cdc649 100644--- a/Libraries/LibUnicode/TextMapping.h+++ b/Libraries/LibUnicode/TextMapping.h@@ -25,32 +25,6 @@ struct UnicodeTextMappingOutput {void (*append_edit)(void*, size_t source_start, size_t source_length, size_t destination_start, size_t destination_length);};-struct UnicodeISODate {- i32 year;- u8 month;- u8 day;-};--struct UnicodeCalendarDate {- bool has_era;- bool has_era_year;- i32 era_year;- i32 year;- u8 month;- u8 day;- u8 day_of_week;- u16 day_of_year;- bool has_week_of_year;- u8 week_of_year;- bool has_year_of_week;- i32 year_of_week;- u8 days_in_week;- u8 days_in_month;- u16 days_in_year;- u8 months_in_year;- bool in_leap_year;-};-extern "C" {void unicode_apply_case_mapping(u16 const* text, size_t length, u8 mapping, u16 const* locale, size_t locale_length, bool preserve_existing, UnicodeTextMappingOutput);void unicode_apply_fullwidth_mapping(u16 const* text, size_t length, UnicodeTextMappingOutput);@@ -66,15 +40,4 @@ size_t unicode_disambiguated_time_zone_offsets(u16 const* time_zone, size_t lengbool unicode_time_zone_transition(u16 const* time_zone, size_t length, i64 seconds, u32 nanoseconds, u8 direction, bool include_given_time, u8 transition_rule, i64* transition_milliseconds);bool unicode_time_zone_display_name(u8 const* locale, size_t locale_length, u8 const* time_zone, size_t time_zone_length, bool in_dst, double time, UnicodeTextMappingOutput);void unicode_default_locale(UnicodeTextMappingOutput);--bool unicode_parse_month_code(u16 const* month_code, size_t length, u8* month_number, bool* is_leap_month);-void unicode_create_month_code(u8 month_number, bool is_leap_month, UnicodeTextMappingOutput);-void unicode_iso_date_to_calendar_date(u8 const* calendar, size_t calendar_length, UnicodeISODate, UnicodeCalendarDate*, UnicodeTextMappingOutput era, UnicodeTextMappingOutput month_code);-bool unicode_calendar_date_to_iso_date(u8 const* calendar, size_t calendar_length, i32 year, u8 month, u8 day, UnicodeISODate*);-bool unicode_iso_year_and_month_code_to_iso_date(u8 const* calendar, size_t calendar_length, i32 year, u16 const* month_code, size_t month_code_length, u8 day, UnicodeISODate*);-bool unicode_calendar_year_and_month_code_to_iso_date(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u16 const* month_code, size_t month_code_length, u8 day, UnicodeISODate*);-u8 unicode_calendar_months_in_year(u8 const* calendar, size_t calendar_length, i32 arithmetic_year);-u8 unicode_calendar_days_in_month(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u8 ordinal_month);-u8 unicode_calendar_max_days_in_month_code(u8 const* calendar, size_t calendar_length, u16 const* month_code, size_t month_code_length);-bool unicode_calendar_year_contains_month_code(u8 const* calendar, size_t calendar_length, i32 arithmetic_year, u16 const* month_code, size_t month_code_length);}