1use std::{
5 any::{Any, TypeId, type_name},
6 fmt,
7 hash::Hasher,
8 marker::PhantomData,
9};
10
11use cranpose_core::{ProvidedValue, hash::default};
12use cranpose_ui_layout::{
13 ConstraintsHold, LayoutDirection, LayoutModifierMeasureResult, WrappedHold,
14};
15
16use super::super::{
17 AnyModifierElement, Constraints, DynModifierElement, ElementMaker, InvalidationKind,
18 Measurable, ModifierNodeContext, NodeCapabilities, Size,
19};
20
21pub const PLAIN_WORDS_MAX: usize = 5;
25
26pub trait PlainElement: fmt::Debug + PartialEq + Sized + 'static {
31 const WORDS: usize;
33
34 const CAPABILITIES: NodeCapabilities;
36
37 const UPDATE_INVALIDATION: Option<InvalidationKind> = None;
40
41 fn to_words(&self, words: &mut [u32]);
43
44 fn from_words(words: &[u32]) -> Self;
46
47 const LAYOUT: Option<&'static PlainLayoutFns> = None;
52
53 fn inspector_name(&self) -> &'static str {
55 type_name::<Self>()
56 }
57
58 fn inspector_properties(&self, _inspector: &mut dyn FnMut(&'static str, String)) {}
60}
61
62pub trait PlainLayout: PlainElement {
65 fn measure(
68 &self,
69 context: &mut dyn ModifierNodeContext,
70 measurable: &dyn Measurable,
71 constraints: Constraints,
72 ) -> LayoutModifierMeasureResult;
73
74 fn prepared(self, _at: PrepareAt) -> Self {
79 self
80 }
81
82 const PREPARES: bool = false;
85
86 fn measure_hold(
90 &self,
91 _density: f32,
92 _constraints: Constraints,
93 _size: Size,
94 _wrapped: WrappedHold,
95 ) -> Option<ConstraintsHold> {
96 None
97 }
98
99 fn intrinsic(&self, measurable: &dyn Measurable, kind: PlainIntrinsic, _density: f32) -> f32 {
102 kind.of(measurable)
103 }
104}
105
106#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct PrepareAt {
109 pub density: f32,
111 pub direction: LayoutDirection,
113}
114
115#[derive(Clone, Copy, Debug, PartialEq)]
117pub enum PlainIntrinsic {
118 MinWidth(f32),
120 MaxWidth(f32),
122 MinHeight(f32),
124 MaxHeight(f32),
126}
127
128impl PlainIntrinsic {
129 pub fn of(self, measurable: &dyn Measurable) -> f32 {
131 match self {
132 Self::MinWidth(height) => measurable.min_intrinsic_width(height),
133 Self::MaxWidth(height) => measurable.max_intrinsic_width(height),
134 Self::MinHeight(width) => measurable.min_intrinsic_height(width),
135 Self::MaxHeight(width) => measurable.max_intrinsic_height(width),
136 }
137 }
138
139 pub fn cross(self) -> f32 {
142 match self {
143 Self::MinWidth(cross)
144 | Self::MaxWidth(cross)
145 | Self::MinHeight(cross)
146 | Self::MaxHeight(cross) => cross,
147 }
148 }
149
150 pub fn at(self, cross: f32) -> Self {
152 match self {
153 Self::MinWidth(_) => Self::MinWidth(cross),
154 Self::MaxWidth(_) => Self::MaxWidth(cross),
155 Self::MinHeight(_) => Self::MinHeight(cross),
156 Self::MaxHeight(_) => Self::MaxHeight(cross),
157 }
158 }
159
160 pub fn is_width(self) -> bool {
162 matches!(self, Self::MinWidth(_) | Self::MaxWidth(_))
163 }
164}
165
166type PrepareFn = fn(&[u32], PrepareAt, &mut [u32]);
168
169type MeasureFn = fn(
170 &[u32],
171 &mut dyn ModifierNodeContext,
172 &dyn Measurable,
173 Constraints,
174) -> LayoutModifierMeasureResult;
175
176pub struct PlainLayoutFns {
179 prepare: Option<PrepareFn>,
181 measure: MeasureFn,
182 measure_hold: fn(&[u32], f32, Constraints, Size, WrappedHold) -> Option<ConstraintsHold>,
183 intrinsic: fn(&[u32], &dyn Measurable, PlainIntrinsic, f32) -> f32,
184}
185
186impl fmt::Debug for PlainLayoutFns {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 f.debug_struct("PlainLayoutFns").finish_non_exhaustive()
189 }
190}
191
192impl PlainLayoutFns {
193 pub const fn of<E: PlainLayout>() -> Self {
195 Self {
196 prepare: if E::PREPARES {
197 Some(|words, at, prepared| {
198 E::from_words(words)
199 .prepared(at)
200 .to_words(&mut prepared[..E::WORDS]);
201 })
202 } else {
203 None
204 },
205 measure: |words, context, measurable, constraints| {
206 E::from_words(words).measure(context, measurable, constraints)
207 },
208 measure_hold: |words, density, constraints, size, wrapped| {
209 E::from_words(words).measure_hold(density, constraints, size, wrapped)
210 },
211 intrinsic: |words, measurable, kind, density| {
212 E::from_words(words).intrinsic(measurable, kind, density)
213 },
214 }
215 }
216
217 #[inline]
221 pub fn prepare(&self, words: &[u32; PLAIN_WORDS_MAX], at: PrepareAt) -> [u32; PLAIN_WORDS_MAX] {
222 match self.prepare {
223 Some(prepare) => {
224 let mut prepared = [0; PLAIN_WORDS_MAX];
225 prepare(words, at, &mut prepared);
226 prepared
227 }
228 None => *words,
229 }
230 }
231
232 #[inline]
234 pub fn measure(
235 &self,
236 words: &[u32],
237 context: &mut dyn ModifierNodeContext,
238 measurable: &dyn Measurable,
239 constraints: Constraints,
240 ) -> LayoutModifierMeasureResult {
241 (self.measure)(words, context, measurable, constraints)
242 }
243
244 pub fn measure_hold(
246 &self,
247 words: &[u32],
248 density: f32,
249 constraints: Constraints,
250 size: Size,
251 wrapped: WrappedHold,
252 ) -> Option<ConstraintsHold> {
253 (self.measure_hold)(words, density, constraints, size, wrapped)
254 }
255
256 pub fn intrinsic(
258 &self,
259 words: &[u32],
260 measurable: &dyn Measurable,
261 kind: PlainIntrinsic,
262 density: f32,
263 ) -> f32 {
264 (self.intrinsic)(words, measurable, kind, density)
265 }
266}
267
268pub struct PlainFns {
271 element_type: TypeId,
272 words: u8,
273 capabilities: NodeCapabilities,
274 update_invalidation: Option<InvalidationKind>,
275 layout: Option<&'static PlainLayoutFns>,
276 type_name: fn() -> &'static str,
277 inspector_name: fn(&[u32]) -> &'static str,
278 inspector_properties: fn(&[u32], &mut dyn FnMut(&'static str, String)),
279}
280
281impl fmt::Debug for PlainFns {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 f.debug_struct("PlainFns").finish_non_exhaustive()
284 }
285}
286
287impl PlainFns {
288 pub fn element_type(&self) -> TypeId {
290 self.element_type
291 }
292
293 pub fn words(&self) -> usize {
295 usize::from(self.words)
296 }
297
298 pub fn capabilities(&self) -> NodeCapabilities {
300 self.capabilities
301 }
302
303 pub fn layout(&self) -> Option<&'static PlainLayoutFns> {
305 self.layout
306 }
307
308 pub fn type_name(&self) -> &'static str {
310 (self.type_name)()
311 }
312
313 pub(in super::super) fn hash_code(&self, words: &[u32]) -> u64 {
314 hash_words(words)
315 }
316
317 pub(in super::super) fn element(&'static self, words: &[u32]) -> DynModifierElement {
318 DynModifierElement::plain(PlainWords::new(self, words))
319 }
320
321 #[inline]
323 pub fn read<E: PlainElement>(&self, words: &[u32]) -> Option<E> {
324 (self.element_type() == TypeId::of::<E>()).then(|| E::from_words(words))
325 }
326}
327
328struct FnsOf<E>(PhantomData<fn() -> E>);
329
330impl<E: PlainElement> FnsOf<E> {
331 const WORDS: u8 = {
332 assert!(E::WORDS <= PLAIN_WORDS_MAX, "a plain element's words fit");
333 E::WORDS as u8
334 };
335
336 const FNS: PlainFns = PlainFns {
337 element_type: TypeId::of::<E>(),
338 words: Self::WORDS,
339 capabilities: E::CAPABILITIES,
340 update_invalidation: E::UPDATE_INVALIDATION,
341 layout: E::LAYOUT,
342 type_name: type_name::<E>,
343 inspector_name: |words| E::from_words(words).inspector_name(),
344 inspector_properties: |words, inspector| {
345 E::from_words(words).inspector_properties(inspector);
346 },
347 };
348}
349
350fn hash_words(words: &[u32]) -> u64 {
353 let mut hasher = default::new();
354 for &word in words {
355 hasher.write_u32(word);
356 }
357 hasher.finish()
358}
359
360fn same_words(a: &[u32], b: &[u32]) -> bool {
365 a.len() == b.len() && a.iter().zip(b).fold(0, |differ, (&x, &y)| differ | (x ^ y)) == 0
366}
367
368pub trait PlainValue {
371 fn fns(&self) -> &'static PlainFns;
373
374 fn write_words(&self, words: &mut [u32]);
376
377 fn equals_words(&self, words: &[u32]) -> bool;
380}
381
382#[derive(Clone, Copy)]
386pub(crate) struct PlainWords {
387 fns: &'static PlainFns,
388 words: [u32; PLAIN_WORDS_MAX],
389 #[expect(dead_code, reason = "its use is the values it never holds")]
394 room: Room,
395}
396
397#[derive(Clone, Copy)]
398#[repr(u8)]
399enum Room {
400 Zero = 0,
401}
402
403impl PlainWords {
404 pub(crate) fn new(fns: &'static PlainFns, words: &[u32]) -> Self {
405 let mut held = [0; PLAIN_WORDS_MAX];
406 held[..words.len()].copy_from_slice(words);
407 Self {
408 fns,
409 words: held,
410 room: Room::Zero,
411 }
412 }
413
414 fn of<E: PlainElement>(element: &E) -> Self {
415 let mut words = [0; PLAIN_WORDS_MAX];
416 element.to_words(&mut words[..E::WORDS]);
417 Self {
418 fns: &FnsOf::<E>::FNS,
419 words,
420 room: Room::Zero,
421 }
422 }
423
424 pub(crate) fn words(&self) -> &[u32] {
425 &self.words[..self.fns.words()]
426 }
427}
428
429impl fmt::Debug for PlainWords {
432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433 f.write_str(self.fns.type_name())
434 }
435}
436
437impl PlainValue for PlainWords {
438 fn fns(&self) -> &'static PlainFns {
439 self.fns
440 }
441
442 fn write_words(&self, words: &mut [u32]) {
443 words.copy_from_slice(self.words());
444 }
445
446 fn equals_words(&self, words: &[u32]) -> bool {
447 same_words(self.words(), words)
448 }
449}
450
451impl AnyModifierElement for PlainWords {
452 fn element_type(&self) -> TypeId {
453 self.fns.element_type()
454 }
455
456 fn maker(&self) -> ElementMaker<'_> {
457 ElementMaker::Plain(self)
458 }
459
460 fn key(&self) -> Option<u64> {
461 None
462 }
463
464 fn capabilities(&self) -> NodeCapabilities {
465 self.fns.capabilities
466 }
467
468 fn hash_code(&self) -> u64 {
469 hash_words(self.words())
470 }
471
472 fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
473 other.equals_plain(self.fns, self.words())
474 }
475
476 fn inspector_name(&self) -> &'static str {
477 (self.fns.inspector_name)(self.words())
478 }
479
480 fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
481 (self.fns.inspector_properties)(self.words(), visitor);
482 }
483
484 fn requires_update(&self) -> bool {
485 false
486 }
487
488 fn auto_invalidates_on_update(&self) -> bool {
489 true
490 }
491
492 fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
493 self.fns.update_invalidation
494 }
495
496 fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
497 Vec::new()
498 }
499
500 fn as_any(&self) -> &dyn Any {
501 self
502 }
503
504 fn equals_plain(&self, fns: &PlainFns, words: &[u32]) -> bool {
505 (std::ptr::eq(fns, self.fns) || fns.element_type() == self.fns.element_type())
508 && same_words(self.words(), words)
509 }
510}
511
512#[inline(never)]
516pub fn plain_element<E: PlainElement>(element: &E) -> DynModifierElement {
517 DynModifierElement::plain(PlainWords::of(element))
518}