Skip to content

Commit

Permalink
no-alloc more crates (#6078)
Browse files Browse the repository at this point in the history
#6076 

This no-allocs everything except for crates that use:
* `Cow`
* `ZeroMap`
  • Loading branch information
robertbastian authored Feb 10, 2025
1 parent 58d8f8b commit ee2814e
Show file tree
Hide file tree
Showing 102 changed files with 720 additions and 292 deletions.
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions components/calendar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ all-features = true
calendrical_calculations = { workspace = true }
displaydoc = { workspace = true }
icu_provider = { workspace = true, features = ["macros"] }
icu_locale_core = { workspace = true }
icu_locale_core = { workspace = true, features = ["alloc"]}
ixdtf = { workspace = true, optional = true }
tinystr = { workspace = true, features = ["alloc", "zerovec"] }
zerovec = { workspace = true, features = ["derive"] }
Expand Down Expand Up @@ -51,8 +51,9 @@ default = ["compiled_data", "ixdtf"]
ixdtf = ["dep:ixdtf"]
logging = ["calendrical_calculations/logging"]
serde = ["dep:serde", "zerovec/serde", "tinystr/serde", "icu_provider/serde"]
datagen = ["serde", "dep:databake", "zerovec/databake", "tinystr/databake"]
datagen = ["serde", "dep:databake", "zerovec/databake", "tinystr/databake", "alloc"]
compiled_data = ["dep:icu_calendar_data"]
alloc = []

[[bench]]
name = "date"
Expand Down
6 changes: 6 additions & 0 deletions components/calendar/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ use crate::any_calendar::{AnyCalendar, IntoAnyCalendar};
use crate::error::DateError;
use crate::week::{WeekCalculator, WeekOf};
use crate::{types, Calendar, DateDuration, DateDurationUnit, Iso};
#[cfg(feature = "alloc")]
use alloc::rc::Rc;
#[cfg(feature = "alloc")]
use alloc::sync::Arc;
use core::fmt;
use core::ops::Deref;
Expand All @@ -30,6 +32,7 @@ impl<C: Calendar> AsCalendar for C {
}
}

#[cfg(feature = "alloc")]
impl<C: AsCalendar> AsCalendar for Rc<C> {
type Calendar = C::Calendar;
#[inline]
Expand All @@ -38,6 +41,7 @@ impl<C: AsCalendar> AsCalendar for Rc<C> {
}
}

#[cfg(feature = "alloc")]
impl<C: AsCalendar> AsCalendar for Arc<C> {
type Calendar = C::Calendar;
#[inline]
Expand Down Expand Up @@ -358,13 +362,15 @@ impl<A: AsCalendar> Date<A> {
/// Wrap the calendar type in `Rc<T>`
///
/// Useful when paired with [`Self::to_any()`] to obtain a `Date<Rc<AnyCalendar>>`
#[cfg(feature = "alloc")]
pub fn wrap_calendar_in_rc(self) -> Date<Rc<A>> {
Date::from_raw(self.inner, Rc::new(self.calendar))
}

/// Wrap the calendar type in `Arc<T>`
///
/// Useful when paired with [`Self::to_any()`] to obtain a `Date<Rc<AnyCalendar>>`
#[cfg(feature = "alloc")]
pub fn wrap_calendar_in_arc(self) -> Date<Arc<A>> {
Date::from_raw(self.inner, Arc::new(self.calendar))
}
Expand Down
1 change: 1 addition & 0 deletions components/calendar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
)]
#![warn(missing_docs)]

#[cfg(feature = "alloc")]
extern crate alloc;

// Make sure inherent docs go first
Expand Down
31 changes: 27 additions & 4 deletions components/calendar/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,13 @@ impl serde::Serialize for WeekdaySet {
S: serde::Serializer,
{
if serializer.is_human_readable() {
crate::week_of::WeekdaySetIterator::new(IsoWeekday::Monday, *self)
.collect::<alloc::vec::Vec<_>>()
.serialize(serializer)
use serde::ser::SerializeSeq;

let mut seq = serializer.serialize_seq(None)?;
for day in crate::week_of::WeekdaySetIterator::new(IsoWeekday::Monday, *self) {
seq.serialize_element(&day)?;
}
seq.end()
} else {
self.0.serialize(serializer)
}
Expand All @@ -236,7 +240,26 @@ impl<'de> serde::Deserialize<'de> for WeekdaySet {
D: serde::Deserializer<'de>,
{
if deserializer.is_human_readable() {
alloc::vec::Vec::<IsoWeekday>::deserialize(deserializer).map(|s| Self::new(&s))
use core::marker::PhantomData;

struct Visitor<'de>(PhantomData<&'de ()>);
impl<'de> serde::de::Visitor<'de> for Visitor<'de> {
type Value = WeekdaySet;
fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
core::write!(f, "a sequence of IsoWeekdays")
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<Self::Value, A::Error> {
let mut set = WeekdaySet::new(&[]);
while let Some(day) = seq.next_element::<IsoWeekday>()? {
set.0 |= day.bit_value();
}
Ok(set)
}
}
deserializer.deserialize_seq(Visitor(PhantomData))
} else {
u8::deserialize(deserializer).map(Self)
}
Expand Down
8 changes: 4 additions & 4 deletions components/casemap/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ all-features = true

[dependencies]
displaydoc = { workspace = true }
icu_collections = { workspace = true }
icu_locale_core = { workspace = true }
icu_collections = { workspace = true, features = ["alloc"] }
icu_locale_core = { workspace = true, features = ["alloc"] }
icu_properties = { workspace = true }
icu_provider = { workspace = true, features = ["macros"] }
potential_utf = { workspace = true, features = ["zerovec"] }
potential_utf = { workspace = true, features = ["alloc", "zerovec"] }
writeable = { workspace = true }
zerovec = { workspace = true, features = ["yoke"] }
zerovec = { workspace = true, features = ["alloc", "yoke"] }

databake = { workspace = true, features = ["derive"], optional = true}
serde = { workspace = true, features = ["derive", "alloc"], optional = true }
Expand Down
2 changes: 1 addition & 1 deletion components/collator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ all-features = true
displaydoc = { workspace = true }
icu_collections = { workspace = true }
icu_normalizer = { workspace = true }
icu_locale_core = { workspace = true }
icu_locale_core = { workspace = true, features = ["alloc"] }
icu_properties = { workspace = true }
icu_provider = { workspace = true, features = ["macros"] }
utf8_iter = { workspace = true }
Expand Down
15 changes: 8 additions & 7 deletions components/collator/src/comparison.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,22 +129,23 @@ impl LocaleSpecificDataHolder {
.unwrap_or_default();

let data_locale = CollationTailoringV1::make_locale(prefs.locale_preferences);
let id = DataIdentifierCow::from_borrowed_and_owned(marker_attributes, data_locale);

let req = DataRequest {
id: id.as_borrowed(),
id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
marker_attributes,
&data_locale,
),
metadata: {
let mut metadata = DataRequestMetadata::default();
metadata.silent = true;
metadata
},
};

let fallback_id =
DataIdentifierCow::from_borrowed_and_owned(Default::default(), data_locale);

let fallback_req = DataRequest {
id: fallback_id.as_borrowed(),
id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
Default::default(),
&data_locale,
),
..Default::default()
};

Expand Down
2 changes: 0 additions & 2 deletions components/collator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,6 @@ mod elements;
mod options;
pub mod provider;

extern crate alloc;

pub use comparison::Collator;
pub use comparison::CollatorBorrowed;
pub use comparison::CollatorPreferences;
Expand Down
3 changes: 2 additions & 1 deletion components/collections/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@ toml = { workspace = true }
criterion = { workspace = true }

[features]
serde = ["dep:serde", "zerovec/serde", "potential_utf/serde"]
serde = ["dep:serde", "zerovec/serde", "potential_utf/serde", "alloc"]
databake = ["dep:databake", "zerovec/databake"]
alloc = ["zerovec/alloc"]

[lib]
bench = false # This option is required for Benchmark CI
Expand Down
5 changes: 3 additions & 2 deletions components/collections/src/codepointinvlist/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use core::iter::FromIterator;
use core::{
convert::TryFrom,
iter::FromIterator,
ops::{Range, RangeBounds, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
};

use super::RangeError;
use crate::codepointinvlist::utils::deconstruct_range;
use crate::codepointinvlist::{CodePointInversionList, CodePointInversionListBuilder};
use crate::codepointinvlist::CodePointInversionList;
use crate::codepointinvlist::CodePointInversionListBuilder;
use potential_utf::PotentialCodePoint;
use zerovec::ZeroVec;

Expand Down
11 changes: 10 additions & 1 deletion components/collections/src/codepointinvlist/cpinvlist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use alloc::format;
#[cfg(feature = "serde")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::{char, ops::RangeBounds, ops::RangeInclusive};
use potential_utf::PotentialCodePoint;
Expand Down Expand Up @@ -33,6 +34,7 @@ const ALL_VEC: ZeroVec<PotentialCodePoint> = zerovec!(PotentialCodePoint; Potent
#[zerovec::skip_derive(Ord)]
#[zerovec::derive(Debug)]
#[derive(Debug, Eq, PartialEq, Clone, Yokeable, ZeroFrom)]
#[cfg_attr(not(feature = "alloc"), zerovec::skip_derive(ZeroMapKV, ToOwned))]
pub struct CodePointInversionList<'data> {
// If we wanted to use an array to keep the memory on the stack, there is an unsafe nightly feature
// https://doc.rust-lang.org/nightly/core/array/trait.FixedSizeArray.html
Expand Down Expand Up @@ -231,7 +233,10 @@ impl<'data> CodePointInversionList<'data> {
.sum::<u32>();
Ok(Self { inv_list, size })
} else {
Err(InvalidSetError(inv_list.to_vec()))
Err(InvalidSetError(
#[cfg(feature = "alloc")]
inv_list.to_vec(),
))
}
}

Expand Down Expand Up @@ -274,6 +279,7 @@ impl<'data> CodePointInversionList<'data> {
///
/// assert!(!lists.iter().any(|set| set.contains32(0x40000)));
/// ```
#[cfg(feature = "alloc")]
pub fn try_from_u32_inversion_list_slice(inv_list: &[u32]) -> Result<Self, InvalidSetError> {
let inv_list_zv: ZeroVec<PotentialCodePoint> = inv_list
.iter()
Expand All @@ -284,6 +290,7 @@ impl<'data> CodePointInversionList<'data> {
}

/// Attempts to convert this list into a fully-owned one. No-op if already fully owned
#[cfg(feature = "alloc")]
pub fn into_owned(self) -> CodePointInversionList<'static> {
CodePointInversionList {
inv_list: self.inv_list.into_owned(),
Expand All @@ -292,6 +299,7 @@ impl<'data> CodePointInversionList<'data> {
}

/// Returns an owned inversion list representing the current [`CodePointInversionList`]
#[cfg(feature = "alloc")]
pub fn get_inversion_list_vec(&self) -> Vec<u32> {
self.as_inversion_list().iter().map(u32::from).collect()
}
Expand Down Expand Up @@ -353,6 +361,7 @@ impl<'data> CodePointInversionList<'data> {
/// Returns the inversion list as a slice
///
/// Public only to the crate, not exposed to public
#[cfg(feature = "alloc")]
pub(crate) fn as_inversion_list(&self) -> &ZeroVec<PotentialCodePoint> {
&self.inv_list
}
Expand Down
11 changes: 7 additions & 4 deletions components/collections/src/codepointinvlist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,26 @@

extern crate alloc;

#[cfg(feature = "alloc")]
#[macro_use]
mod builder;
#[cfg(feature = "alloc")]
mod conversions;
mod cpinvlist;
mod utils;

use alloc::vec::Vec;

#[cfg(feature = "alloc")]
pub use builder::CodePointInversionListBuilder;
pub use cpinvlist::CodePointInversionList;
pub use cpinvlist::CodePointInversionListULE;
use displaydoc::Display;

#[derive(Display, Debug)]
/// A CodePointInversionList was constructed with an invalid inversion list
#[displaydoc("Invalid set: {0:?}")]
pub struct InvalidSetError(pub Vec<potential_utf::PotentialCodePoint>);
#[cfg_attr(feature = "alloc", displaydoc("Invalid set: {0:?}"))]
pub struct InvalidSetError(
#[cfg(feature = "alloc")] pub alloc::vec::Vec<potential_utf::PotentialCodePoint>,
);

/// A CodePointInversionList was constructed from an invalid range
#[derive(Display, Debug)]
Expand Down
Loading

0 comments on commit ee2814e

Please sign in to comment.