1use std::cmp::Ordering;
4
5use super::RootSize;
6use crate::Error;
7
8const QUANTA_PER_CSS_PIXEL: i64 = 1024;
9
10pub(crate) fn nearest_spatial_quanta(value: f64) -> Result<i64, Error> {
11 LayoutScalar::from_css_pixels(value, SpatialRounding::NearestEven).map(|value| value.0)
12}
13
14pub(crate) fn ceil_spatial_quanta(value: f64) -> Result<i64, Error> {
15 LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil).map(|value| value.0)
16}
17
18#[cfg(test)]
19thread_local! {
20 static FORCED_RESERVATION_FAILURE: std::cell::Cell<Option<ReservationStage>> = const { std::cell::Cell::new(None) };
21}
22
23#[cfg(test)]
24pub(crate) fn force_reservation_failure(stage: ReservationStage) {
25 FORCED_RESERVATION_FAILURE.with(|forced| forced.set(Some(stage)));
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
29pub(crate) struct LayoutScalar(i64);
30
31#[derive(Debug, Clone, Copy)]
32pub(crate) enum SpatialRounding {
33 Floor,
34 Ceil,
35 NearestEven,
36}
37
38impl LayoutScalar {
39 pub(crate) const fn from_quanta(value: i64) -> Self {
40 Self(value)
41 }
42
43 pub(crate) const fn quanta(self) -> i64 {
44 self.0
45 }
46
47 fn is_nonnegative(self) -> bool {
48 self.0 >= 0
49 }
50
51 fn canonical_dimension(self) -> Option<u32> {
52 let value = u128::try_from(self.0).ok()?;
53 let quantum = QUANTA_PER_CSS_PIXEL as u128;
54 let rounded = value.checked_add(quantum - 1)? / quantum;
55 u32::try_from(rounded).ok()
56 }
57
58 pub(crate) fn from_css_pixels(value: f64, rounding: SpatialRounding) -> Result<Self, Error> {
59 let bits = value.to_bits();
60 let exponent_bits = ((bits >> 52) & 0x7ff) as u16;
61 if exponent_bits == 0x7ff {
62 return Err(Error::Render("layout spatial input must be finite".into()));
63 }
64 let fraction = bits & 0x000f_ffff_ffff_ffff;
65 if exponent_bits == 0 && fraction == 0 {
66 return Ok(Self(0));
67 }
68 let negative = bits >> 63 != 0;
69 let significand = if exponent_bits == 0 {
70 u128::from(fraction)
71 } else {
72 u128::from((1_u64 << 52) | fraction)
73 };
74 let shift = if exponent_bits == 0 {
75 -1064
76 } else {
77 i32::from(exponent_bits) - 1065
78 };
79 let (quotient, remainder_order) = if shift >= 0 {
80 let shift = u32::try_from(shift)
81 .map_err(|_| Error::Render("layout quantum shift overflowed".into()))?;
82 if shift >= u128::BITS || significand > (u128::MAX >> shift) {
83 return Err(Error::Render("layout quantum conversion overflowed".into()));
84 }
85 (significand << shift, None)
86 } else {
87 let denominator_shift = shift.unsigned_abs();
88 if denominator_shift >= 128 {
89 (0, Some(Ordering::Less))
90 } else {
91 let denominator = 1_u128 << denominator_shift;
92 let quotient = significand / denominator;
93 let remainder = significand % denominator;
94 (
95 quotient,
96 (remainder != 0).then(|| remainder.cmp(&(denominator / 2))),
97 )
98 }
99 };
100 let increment = match remainder_order {
101 None => false,
102 Some(order) => match rounding {
103 SpatialRounding::Floor => negative,
104 SpatialRounding::Ceil => !negative,
105 SpatialRounding::NearestEven => {
106 order == Ordering::Greater || (order == Ordering::Equal && quotient % 2 != 0)
107 }
108 },
109 };
110 let magnitude = quotient
111 .checked_add(u128::from(increment))
112 .ok_or_else(|| Error::Render("layout quantum rounding overflowed".into()))?;
113 if negative {
114 if magnitude == 1_u128 << 63 {
115 Ok(Self(i64::MIN))
116 } else {
117 let magnitude = i64::try_from(magnitude)
118 .map_err(|_| Error::Render("layout quantum conversion overflowed".into()))?;
119 Ok(Self(-magnitude))
120 }
121 } else {
122 i64::try_from(magnitude)
123 .map(Self)
124 .map_err(|_| Error::Render("layout quantum conversion overflowed".into()))
125 }
126 }
127}
128
129#[allow(
130 dead_code,
131 reason = "the closed role order is part of canonical structural identity"
132)]
133#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
134#[repr(u16)]
135#[non_exhaustive]
137pub enum AddressRole {
138 Root,
140 RootTitle,
142 RootSubtitle,
144 RootBody,
146 RootCaption,
148 PlotBody,
150 CanvasBody,
152 CanvasGrid,
154 FacetGrid,
156 CanvasSharedLegend,
158 CanvasHeader,
160 CanvasRowTitle,
162 CanvasRangeGroup,
164 CanvasCell,
166 FacetHeader,
168 FacetRowTitle,
170 FacetRangeGroup,
172 FacetCell,
174 DataPanel,
176 PanelInterior,
178 SpecializedInterior,
180 MarkLayer,
182 MarkItem,
184 HeatmapCell,
186 HeatmapMergedRow,
188 HeatmapValueLabel,
190 HeatmapHighlight,
192 BeeswarmCategory,
194 BeeswarmPoint,
196 MarginalCentral,
198 MarginalTop,
200 MarginalRight,
202 MatrixCell,
204 MatrixMark,
206 CategoricalCategory,
208 CategoricalSeriesSlot,
210 CategoricalBodyMark,
212 CategoricalInterval,
214 CategoricalValueLabel,
216 WaterfallBar,
218 WaterfallConnector,
220 WaterfallBaseLabel,
222 WaterfallTerminalLabel,
224 LegendSection,
226 LegendTitle,
228 LegendEntry,
230 LegendKey,
232 LegendLabel,
234 GuideTitle,
236 GuideGradient,
238 GuideLabel,
240 GuideMissingBlock,
242 Surface,
244 TextPanelContent,
246 TextPanelTitle,
248 TextPanelBody,
250 InsideGuide,
252 Annotation,
254 AnnotationTarget,
256 OtherOverlay,
258 AxisTop,
260 AxisRight,
262 AxisBottom,
264 AxisLeft,
266 AxisTitle,
268 OutsideGuideTop,
270 OutsideGuideRight,
272 OutsideGuideBottom,
274 OutsideGuideLeft,
276 OutsideGuideAuto,
278 PreferenceMetric,
280 Text,
282 Glyph,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
287pub struct AddressSegment {
289 pub role: AddressRole,
291 pub slot_index: u32,
293}
294
295#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
296pub struct ComponentAddress {
298 root: AddressSegment,
299 descendants: Option<std::sync::Arc<Vec<AddressSegment>>>,
300}
301
302impl std::fmt::Debug for ComponentAddress {
303 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304 formatter
305 .debug_struct("ComponentAddress")
306 .field("root", &self.root)
307 .field("descendants", &self.descendants())
308 .finish()
309 }
310}
311
312impl ComponentAddress {
313 pub fn segments(&self) -> impl Iterator<Item = AddressSegment> + '_ {
315 std::iter::once(self.root).chain(self.descendants().iter().copied())
316 }
317
318 fn descendants(&self) -> &[AddressSegment] {
319 self.descendants.as_deref().map_or(&[], Vec::as_slice)
320 }
321
322 pub(crate) fn leaf_role(&self) -> AddressRole {
323 self.descendants()
324 .last()
325 .map_or(self.root.role, |segment| segment.role)
326 }
327
328 pub(crate) fn leaf_slot_index(&self) -> u32 {
329 self.descendants().last().unwrap_or(&self.root).slot_index
330 }
331
332 pub(crate) fn under_grid(&self, grid: AddressRole) -> Result<Self, Error> {
333 let [leaf] = self.descendants() else {
334 return Err(Error::Render(
335 "child owner must be one root-local cell".into(),
336 ));
337 };
338 Self::root()
339 .child(grid, 0)?
340 .child(leaf.role, leaf.slot_index)
341 }
342 fn is_within(&self, owner: &Self) -> bool {
343 self.root == owner.root && self.descendants().starts_with(owner.descendants())
344 }
345 pub(crate) fn root() -> Self {
346 Self {
347 root: AddressSegment {
348 role: AddressRole::Root,
349 slot_index: 0,
350 },
351 descendants: None,
352 }
353 }
354
355 pub(crate) fn child(&self, role: AddressRole, slot_index: u32) -> Result<Self, Error> {
356 let count = self
357 .descendants()
358 .len()
359 .checked_add(1)
360 .ok_or_else(|| Error::Render("component address length overflowed".into()))?;
361
362 let mut descendants = Vec::new();
366 crate::operation::capacity::<AddressSegment>(0, 0, count)?;
367 descendants.try_reserve_exact(count).map_err(|error| {
368 Error::Render(
369 format!("layout could not reserve canonical component address: {error}").into(),
370 )
371 })?;
372 descendants.extend_from_slice(self.descendants());
373 descendants.push(AddressSegment { role, slot_index });
374 Ok(Self {
375 root: self.root,
376 descendants: Some(std::sync::Arc::new(descendants)),
377 })
378 }
379
380 pub(crate) fn canonical_text_cmp(&self, other: &Self) -> Ordering {
381 let root = (
382 self.root.role.text_traversal_ordinal(),
383 self.root.slot_index,
384 )
385 .cmp(&(
386 other.root.role.text_traversal_ordinal(),
387 other.root.slot_index,
388 ));
389 if root != Ordering::Equal {
390 return root;
391 }
392 self.descendants()
393 .iter()
394 .map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index))
395 .cmp(
396 other
397 .descendants()
398 .iter()
399 .map(|segment| (segment.role.text_traversal_ordinal(), segment.slot_index)),
400 )
401 }
402}
403
404impl AddressRole {
405 const fn text_traversal_ordinal(self) -> u16 {
406 match self {
407 Self::RootCaption => u16::MAX,
409 _ => self as u16,
410 }
411 }
412}
413
414pub(crate) struct PreparedStage<'a> {
415 resources: &'a mut crate::font::canonical::OperationContext,
416 reservations: &'a mut ReservationDriver,
417}
418
419impl PreparedStage<'_> {
420 pub(crate) fn reserve_scalar_presence_map(&mut self) -> Result<Vec<u64>, Error> {
421 const SCALAR_MAP_WORDS: usize = 0x11_0000 / u64::BITS as usize;
422 let mut presence = Vec::new();
423 self.reserve_prepared(
424 &mut presence,
425 SCALAR_MAP_WORDS,
426 "Unicode scalar presence map",
427 )?;
428 presence.resize(SCALAR_MAP_WORDS, 0);
429 Ok(presence)
430 }
431
432 pub(crate) fn reserve_prepared<T>(
433 &mut self,
434 values: &mut Vec<T>,
435 additional: usize,
436 payload: &str,
437 ) -> Result<(), Error> {
438 self.reservations.reserve_additional(
439 ReservationStage::Prepared,
440 values,
441 additional,
442 payload,
443 )
444 }
445
446 pub(crate) fn reserve_prepared_string(
447 &mut self,
448 value: &mut String,
449 additional: usize,
450 payload: &str,
451 ) -> Result<(), Error> {
452 self.reservations
453 .enter(ReservationStage::Prepared, payload)?;
454 crate::operation::capacity::<u8>(value.capacity(), value.len(), additional)?;
455 value
456 .try_reserve_exact(additional)
457 .map_err(|error| reservation_error(ReservationStage::Prepared, payload, error))
458 }
459
460 pub(crate) fn operation(&self) -> crate::font::canonical::OperationContext {
461 self.resources.clone()
462 }
463}
464
465pub(crate) struct FinalStage<'a> {
466 reservations: &'a mut ReservationDriver,
467}
468
469impl FinalStage<'_> {
470 pub(crate) fn reserve_capture<T>(
471 &mut self,
472 values: &mut Vec<T>,
473 additional: usize,
474 payload: &str,
475 ) -> Result<(), Error> {
476 let needed = values
477 .len()
478 .checked_add(additional)
479 .ok_or_else(|| Error::Render(format!("{payload}: capture length overflow").into()))?;
480 if needed <= values.capacity() {
481 return Ok(());
482 }
483 let capacity = needed.max(values.capacity().saturating_mul(2));
484
485 self.reserve_final(values, capacity - values.len(), payload)
486 }
487
488 pub(crate) fn reserve_final<T>(
489 &mut self,
490 values: &mut Vec<T>,
491 additional: usize,
492 payload: &str,
493 ) -> Result<(), Error> {
494 self.reservations
495 .reserve_additional(ReservationStage::Final, values, additional, payload)
496 }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub(crate) enum ReservationStage {
501 Prepared,
502 Measured,
503 Final,
504}
505
506impl ReservationStage {
507 pub(crate) fn number(self) -> u8 {
508 match self {
509 Self::Prepared => 1,
510 Self::Measured => 2,
511 Self::Final => 3,
512 }
513 }
514}
515
516struct ReservationDriver {
517 phase: ReservationStage,
518}
519
520impl ReservationDriver {
521 fn new() -> Self {
522 Self {
523 phase: ReservationStage::Prepared,
524 }
525 }
526
527 fn reserve_additional<T>(
528 &mut self,
529 stage: ReservationStage,
530 values: &mut Vec<T>,
531 additional: usize,
532 payload: &str,
533 ) -> Result<(), Error> {
534 self.enter(stage, payload)?;
535 crate::operation::capacity::<T>(values.capacity(), values.len(), additional)?;
536 values
537 .try_reserve_exact(additional)
538 .map_err(|error| reservation_error(stage, payload, error))
539 }
540
541 fn enter(&mut self, stage: ReservationStage, payload: &str) -> Result<(), Error> {
542 if self.phase != stage {
543 return Err(Error::Render(
544 format!(
545 "layout reservation stage {} was requested out of order",
546 stage.number()
547 )
548 .into(),
549 ));
550 }
551 #[cfg(test)]
552 if FORCED_RESERVATION_FAILURE.with(|forced| {
553 if forced.get() == Some(stage) {
554 forced.set(None);
555 true
556 } else {
557 false
558 }
559 }) {
560 return Err(reservation_error(stage, payload, "forced test refusal"));
561 }
562 let _ = payload;
563 Ok(())
564 }
565}
566
567fn reservation_error(
568 stage: ReservationStage,
569 payload: &str,
570 error: impl std::fmt::Display,
571) -> Error {
572 Error::Render(
573 format!(
574 "layout reservation stage {} could not reserve {payload}: {error}",
575 stage.number()
576 )
577 .into(),
578 )
579}
580
581#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub(crate) enum RootRequest {
584 Natural,
585 ExactWidth(u32),
586 MaxWidth(u32),
587 ExactSize { width: u32, height: u32 },
588 Physical(RootSize),
589}
590
591impl RootRequest {
592 pub(crate) fn select_width(self, preference: f64) -> Result<u32, Error> {
593 self.validate()?;
594 if let Some(width) = self.exact_width() {
595 return Ok(width);
596 }
597 if !preference.is_finite() || preference <= 0.0 {
598 return Err(Error::Render(
599 "natural root width preference must be finite and positive".into(),
600 ));
601 }
602 root_dimension(match self {
603 Self::MaxWidth(maximum) => preference.min(f64::from(maximum)),
604 _ => preference,
605 })
606 }
607 pub(crate) const fn exact_width(self) -> Option<u32> {
608 match self {
609 Self::Natural | Self::MaxWidth(_) | Self::Physical(_) => None,
610 Self::ExactWidth(width) | Self::ExactSize { width, .. } => Some(width),
611 }
612 }
613 pub(crate) fn exact_size(self) -> Option<RootSize> {
614 match self {
615 Self::ExactSize { width, height } => Some(RootSize::new(width, height)),
616 Self::Physical(size) => Some(size),
617 _ => None,
618 }
619 }
620
621 pub(crate) const fn automatic_height(self) -> bool {
622 !matches!(self, Self::ExactSize { .. } | Self::Physical(_))
623 }
624
625 #[cfg(test)]
626 pub(crate) fn assigned_size(self) -> Result<RootSize, Error> {
627 let size = self.exact_size().ok_or_else(|| {
628 Error::Render("root content measurement must provide both finite dimensions".into())
629 })?;
630 size.dimensions()?;
631 Ok(size)
632 }
633
634 #[cfg(test)]
635 pub(crate) fn dimensions(self) -> Result<(f64, f64), Error> {
636 self.assigned_size()?.dimensions()
637 }
638
639 fn validate(self) -> Result<(), Error> {
640 if let Some(size) = self.exact_size() {
641 size.dimensions()?;
642 } else if self.exact_width() == Some(0) || matches!(self, Self::MaxWidth(0)) {
643 return Err(Error::Render(
644 "layout root dimensions must be finite and positive".into(),
645 ));
646 }
647 Ok(())
648 }
649
650 fn validate_size(self, size: RootSize) -> Result<(), Error> {
651 let (width, height) = size.dimensions()?;
652 if matches!(self, Self::MaxWidth(maximum) if width > f64::from(maximum)) {
653 return Err(Error::Render(
654 "measured root width exceeds its maximum-width sizing request".into(),
655 ));
656 }
657 if let Some(exact) = self.exact_size() {
658 if size != exact {
659 return Err(Error::Render(
660 "measured root dimensions do not match the exact assignment".into(),
661 ));
662 }
663 } else if width.fract() != 0.0
664 || height.fract() != 0.0
665 || self
666 .exact_width()
667 .is_some_and(|exact| width.to_bits() != f64::from(exact).to_bits())
668 {
669 return Err(Error::Render(
670 "measured root dimensions do not match the sizing request".into(),
671 ));
672 }
673 Ok(())
674 }
675}
676
677pub(crate) struct MeasuredLayout<Plan> {
678 size: RootSize,
679 plan: Plan,
680}
681
682impl<Plan> MeasuredLayout<Plan> {
683 pub(crate) fn new(size: RootSize, plan: Plan) -> Self {
684 Self { size, plan }
685 }
686}
687
688struct RootAllocation<Plan> {
689 request: RootRequest,
690 size: RootSize,
691 plan: Plan,
692}
693
694pub(crate) struct FrozenRoot<Plan> {
696 allocation: Box<[RootAllocation<Plan>; 1]>,
697}
698
699impl<Plan> FrozenRoot<Plan> {
700 pub(crate) fn size(&self) -> RootSize {
701 self.allocation[0]
702 .request
703 .validate_size(self.allocation[0].size)
704 .expect("frozen root satisfies its original sizing request");
705 self.allocation[0].size
706 }
707 pub(crate) fn plan(&self) -> &Plan {
708 &self.allocation[0].plan
709 }
710}
711
712mod feedback;
713mod tracks;
714pub(crate) use feedback::TrialOutcome;
715pub(crate) use feedback::{ChildFeedback, ChildFeedbackInputs};
716pub(crate) use feedback::{
717 FeedbackKind, FeedbackRequestId, FeedbackRound, FitKind, FrameRequirements,
718};
719pub(crate) use tracks::{allocate_grid_axis, allocate_tracks, GridRequirement, TrackSpec};
720
721pub(crate) fn required_length(value: f64) -> Result<f64, Error> {
722 let length = LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?;
723 if !length.is_nonnegative() {
724 return Err(Error::Render(
725 "required layout length must be nonnegative".into(),
726 ));
727 }
728 #[expect(
729 clippy::cast_precision_loss,
730 reason = "required guide lengths are subsequently checked against exact u32 root constraints"
731 )]
732 let value = length.0 as f64 / 1024.0;
733 Ok(value)
734}
735
736pub(crate) fn root_dimension(value: f64) -> Result<u32, Error> {
737 LayoutScalar::from_css_pixels(value, SpatialRounding::Ceil)?
738 .canonical_dimension()
739 .filter(|value| *value > 0)
740 .ok_or_else(|| {
741 Error::Render(
742 "natural root dimension is not representable as positive CSS pixels".into(),
743 )
744 })
745}
746
747#[cfg(test)]
749pub(crate) fn plan_root<Plan, FinalPlan, Prepared>(
750 request: RootRequest,
751 prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
752 measure: impl FnMut(
753 &Prepared,
754 RootRequest,
755 &mut FeedbackRound,
756 ) -> Result<MeasuredLayout<Plan>, Error>,
757 finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
758) -> Result<FrozenRoot<FinalPlan>, Error> {
759 plan_root_with_results(request, false, prepare, measure, finalize)
760}
761
762#[expect(
763 clippy::too_many_lines,
764 reason = "the complete root prepare, feedback, seal and freeze lifecycle stays ordered"
765)]
766pub(crate) fn plan_root_with_results<Plan, FinalPlan, Prepared>(
767 request: RootRequest,
768 capture_results: bool,
769 prepare: impl FnOnce(&mut PreparedStage<'_>) -> Result<Prepared, Error>,
770 mut measure: impl FnMut(
771 &Prepared,
772 RootRequest,
773 &mut FeedbackRound,
774 ) -> Result<MeasuredLayout<Plan>, Error>,
775 finalize: impl FnOnce(&Prepared, RootSize, Plan, &mut FinalStage<'_>) -> Result<FinalPlan, Error>,
776) -> Result<FrozenRoot<FinalPlan>, Error> {
777 use crate::{errors::OperationPhase, operation};
778 request.validate()?;
779 operation::phase(OperationPhase::Prepare)?;
780 let mut assigned = request;
781 let mut resources = crate::font::canonical::OperationContext::with_results(capture_results);
782 let mut reservations = ReservationDriver::new();
783 let mut prepared_stage = PreparedStage {
784 resources: &mut resources,
785 reservations: &mut reservations,
786 };
787
788 let prepared = prepare(&mut prepared_stage)?;
789 operation::phase(OperationPhase::Layout)?;
790
791 reservations.phase = ReservationStage::Measured;
792 let mut history = Vec::new();
793 reservations.reserve_additional(
794 ReservationStage::Measured,
795 &mut history,
796 1,
797 "measured root plan",
798 )?;
799 let measured = loop {
800 operation::checkpoint()?;
801 operation::work(1)?;
802 let mut round = FeedbackRound::new(history.last(), history.len())?;
803 round.observe_root_request(request)?;
804 if let Some(size) = assigned.exact_size() {
805 let (width, height) = size.dimensions()?;
806 round.observe_number(width)?;
807 round.observe_number(height)?;
808 } else if let Some(width) = assigned.exact_width() {
809 round.observe_number(f64::from(width))?;
810 }
811 let result = measure(&prepared, assigned, &mut round)?;
812 assigned.validate_size(result.size)?;
813 request.validate_size(result.size)?;
814 if assigned.automatic_height() {
816 assigned = RootRequest::ExactWidth(root_dimension(result.size.dimensions()?.0)?);
817 }
818 let state = round.finish();
819 if let Some(error) = state.terminal_error() {
820 return Err(error);
821 }
822 if state.feedback_unchanged() {
825 if let Some(error) = state.unchanged_error() {
826 return Err(error);
827 }
828 break result;
829 }
830 if state.repeats_history(&history) {
831 use crate::errors::{
832 Diagnostic, DiagnosticKind, ErrorContext, NonConvergenceReason, OperationPhase,
833 };
834 return Err(Error::Render(
835 Diagnostic::new(
836 DiagnosticKind::NonConvergence {
837 algorithm: "root layout feedback",
838 iterations: history.len() + 1,
839 reason: NonConvergenceReason::Cycle,
840 },
841 "layout root feedback cycle detected",
842 )
843 .with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
844 ));
845 }
846 if history.len() == 7 {
847 use crate::errors::{
848 BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase,
849 };
850 return Err(Error::Render(
851 Diagnostic::new(
852 DiagnosticKind::BudgetExceeded {
853 resource: BudgetResource::LayoutRounds,
854 required: 9,
855 limit: 8,
856 },
857 "layout root feedback exhausted eight rounds",
858 )
859 .with_context(ErrorContext::new().with_operation(OperationPhase::Layout)),
860 ));
861 }
862 reservations.reserve_additional(
863 ReservationStage::Measured,
864 &mut history,
865 1,
866 "root feedback state",
867 )?;
868 history.push(state);
869 };
870 let assigned = measured.size;
871
872 operation::phase(OperationPhase::Freeze)?;
873 resources
874 .seal_fonts()
875 .map_err(|error| Error::from(error).with_prefix("accepted root font sealing"))?;
876 reservations.phase = ReservationStage::Final;
877 let mut allocation = Vec::new();
878 let mut final_stage = FinalStage {
879 reservations: &mut reservations,
880 };
881 final_stage.reserve_final(&mut allocation, 1, "frozen root plan")?;
882 let plan = finalize(&prepared, assigned, measured.plan, &mut final_stage)?;
883 operation::checkpoint()?;
884 drop(prepared);
885 drop(history);
886 drop(resources);
887 allocation.push(RootAllocation {
888 request,
889 size: assigned,
890 plan,
891 });
892 let allocation = allocation
893 .into_boxed_slice()
894 .try_into()
895 .unwrap_or_else(|_| unreachable!("one frozen root allocation"));
896 Ok(FrozenRoot { allocation })
897}
898
899#[cfg(test)]
900#[path = "kernel/tests.rs"]
901mod tests;