From 3d228bfc8466aba9697c25387c6c26b07fbbe2f9 Mon Sep 17 00:00:00 2001 From: James Ide Date: Wed, 2 Dec 2026 02:20:38 -0800 Subject: [PATCH] Use exact float equality in text measurement cache keys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Text measurement keys can compare equal and hash differently for neighboring floats or for two representations of an unset value. An infinite paragraph font limit can leave an entry in the LRU map after eviction because the key compares unequal to itself. Compare cache floats exactly and hash their canonical integer encodings, including both coordinates of a present shadow offset. Combine float pairs on 64-bit platforms with 32-bit floats and fold attribute optionals into one presence mask. On Apple M6, the four-fragment size, line and prepared hashes retire 1108.08 → 1075.08, 1083.09 → 1046.08 and 1731.12 → 1631.11 instructions, respectively. The ordinary attribute hash fixtures match upstream within the measured noise. The Fantom text layout and attributed string suites and Android text unit tests pass. The four float regressions fail on upstream and detect the corresponding mutations. Signed-off-by: James Ide --- .../attributedstring/ParagraphAttributes.cpp | 21 ++- .../attributedstring/ParagraphAttributes.h | 41 +++-- .../attributedstring/TextAttributes.cpp | 41 ++++- .../attributedstring/TextAttributes.h | 5 + .../textlayoutmanager/TextMeasureCache.h | 167 ++++++++++++++---- .../tests/TextLayoutManagerTest.cpp | 150 ++++++++++++++++ .../ReactCommon/react/utils/FloatComparison.h | 7 + .../ReactAndroidFrameworksCxx.api | 15 +- .../api-snapshots/ReactAppleFrameworksCxx.api | 15 +- .../ReactCommonFrameworksCxx.api | 15 +- 10 files changed, 414 insertions(+), 63 deletions(-) diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.cpp b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.cpp index c6bbbf364ce4..3551b6615674 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.cpp +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.cpp @@ -15,6 +15,23 @@ namespace facebook::react { bool ParagraphAttributes::operator==(const ParagraphAttributes& rhs) const { + return equals(rhs); +} + +bool ParagraphAttributes::equalsForTextCache( + const ParagraphAttributes& rhs) const { + return equals(rhs); +} + +template +bool ParagraphAttributes::equals(const ParagraphAttributes& rhs) const { + const auto equal = [](Float lhs, Float rhs) { + if constexpr (Exact) { + return exactFloatEquality(lhs, rhs); + } + return floatEquality(lhs, rhs); + }; + return std::tie( maximumNumberOfLines, ellipsizeMode, @@ -37,8 +54,8 @@ bool ParagraphAttributes::operator==(const ParagraphAttributes& rhs) const { rhs.lineBreak, rhs.wordBreak, rhs.textAlignVertical) && - floatEquality(minimumFontSize, rhs.minimumFontSize) && - floatEquality(minimumFontScale, rhs.minimumFontScale); + equal(minimumFontSize, rhs.minimumFontSize) && + equal(minimumFontScale, rhs.minimumFontScale); } #pragma mark - DebugStringConvertible diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h index 7a8d8dba13a1..c738755ecef5 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/ParagraphAttributes.h @@ -99,35 +99,48 @@ class ParagraphAttributes : public DebugStringConvertible { std::optional textAlignVertical{}; bool operator==(const ParagraphAttributes &rhs) const; + bool equalsForTextCache(const ParagraphAttributes &rhs) const; #pragma mark - DebugStringConvertible #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList getDebugProps() const override; #endif + + private: + template + bool equals(const ParagraphAttributes &rhs) const; }; +namespace detail { + +template +size_t hashParagraphAttributes(const ParagraphAttributes &attributes, FloatProjection projectFloat) +{ + return facebook::react::hash_combine( + attributes.maximumNumberOfLines, + attributes.ellipsizeMode, + attributes.textBreakStrategy, + attributes.textWidthMode, + attributes.adjustsFontSizeToFit, + projectFloat(attributes.minimumFontSize), + attributes.includeFontPadding, + attributes.android_hyphenationFrequency, + attributes.lineBreak, + attributes.wordBreak, + projectFloat(attributes.minimumFontScale), + attributes.textAlignVertical); +} + +} // namespace detail } // namespace facebook::react namespace std { - template <> struct hash { size_t operator()(const facebook::react::ParagraphAttributes &attributes) const { - return facebook::react::hash_combine( - attributes.maximumNumberOfLines, - attributes.ellipsizeMode, - attributes.textBreakStrategy, - attributes.textWidthMode, - attributes.adjustsFontSizeToFit, - attributes.minimumFontSize, - attributes.includeFontPadding, - attributes.android_hyphenationFrequency, - attributes.lineBreak, - attributes.wordBreak, - attributes.minimumFontScale, - attributes.textAlignVertical); + return facebook::react::detail::hashParagraphAttributes(attributes, std::identity{}); } }; } // namespace std diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.cpp b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.cpp index 5d27865ee84c..f92bf45df768 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.cpp +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.cpp @@ -133,6 +133,32 @@ void TextAttributes::apply(TextAttributes textAttributes) { #pragma mark - Operators bool TextAttributes::operator==(const TextAttributes& rhs) const { + return textShadowOffset == rhs.textShadowOffset && equals(rhs); +} + +bool TextAttributes::equalsForTextCache(const TextAttributes& rhs) const { + if (textShadowOffset.has_value() != rhs.textShadowOffset.has_value()) { + return false; + } + if (textShadowOffset && + (!exactFloatEquality( + textShadowOffset->width, rhs.textShadowOffset->width) || + !exactFloatEquality( + textShadowOffset->height, rhs.textShadowOffset->height))) { + return false; + } + return equals(rhs); +} + +template +bool TextAttributes::equals(const TextAttributes& rhs) const { + const auto equal = [](Float lhs, Float rhs) { + if constexpr (Exact) { + return exactFloatEquality(lhs, rhs); + } + return floatEquality(lhs, rhs); + }; + return std::tie( foregroundColor, backgroundColor, @@ -150,7 +176,6 @@ bool TextAttributes::operator==(const TextAttributes& rhs) const { textDecorationColor, textDecorationLineType, textDecorationStyle, - textShadowOffset, textShadowColor, isHighlighted, isPressable, @@ -176,7 +201,6 @@ bool TextAttributes::operator==(const TextAttributes& rhs) const { rhs.textDecorationColor, rhs.textDecorationLineType, rhs.textDecorationStyle, - rhs.textShadowOffset, rhs.textShadowColor, rhs.isHighlighted, rhs.isPressable, @@ -185,13 +209,12 @@ bool TextAttributes::operator==(const TextAttributes& rhs) const { rhs.role, rhs.textTransform, rhs.textEffects) && - floatEquality(maxFontSizeMultiplier, rhs.maxFontSizeMultiplier) && - floatEquality(opacity, rhs.opacity) && - floatEquality(fontSize, rhs.fontSize) && - floatEquality(fontSizeMultiplier, rhs.fontSizeMultiplier) && - floatEquality(letterSpacing, rhs.letterSpacing) && - floatEquality(lineHeight, rhs.lineHeight) && - floatEquality(textShadowRadius, rhs.textShadowRadius); + equal(maxFontSizeMultiplier, rhs.maxFontSizeMultiplier) && + equal(opacity, rhs.opacity) && equal(fontSize, rhs.fontSize) && + equal(fontSizeMultiplier, rhs.fontSizeMultiplier) && + equal(letterSpacing, rhs.letterSpacing) && + equal(lineHeight, rhs.lineHeight) && + equal(textShadowRadius, rhs.textShadowRadius); } TextAttributes TextAttributes::defaultTextAttributes() { diff --git a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h index 49e3d5deaa56..167b641b7304 100644 --- a/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h +++ b/packages/react-native/ReactCommon/react/renderer/attributedstring/TextAttributes.h @@ -107,12 +107,17 @@ class TextAttributes : public DebugStringConvertible { #pragma mark - Operators bool operator==(const TextAttributes &rhs) const; + bool equalsForTextCache(const TextAttributes &rhs) const; #pragma mark - DebugStringConvertible #if RN_DEBUG_STRING_CONVERTIBLE SharedDebugStringConvertibleList getDebugProps() const override; #endif + + private: + template + bool equals(const TextAttributes &rhs) const; }; } // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h index c1eb566133d2..b89f0fa5d153 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/TextMeasureCache.h @@ -9,6 +9,12 @@ #include +#include +#include +#include +#include +#include + #include #include #include @@ -150,38 +156,104 @@ inline bool areTextAttributesEquivalentLayoutWise(const TextAttributes &lhs, con rhs.lineBreakMode, rhs.layoutDirection, rhs.alignment) && - floatEquality(lhs.fontSize, rhs.fontSize) && floatEquality(lhs.fontSizeMultiplier, rhs.fontSizeMultiplier) && - floatEquality(lhs.letterSpacing, rhs.letterSpacing) && floatEquality(lhs.lineHeight, rhs.lineHeight) && - floatEquality(lhs.maxFontSizeMultiplier, rhs.maxFontSizeMultiplier) && lhs.textEffects == rhs.textEffects; + exactFloatEquality(lhs.fontSize, rhs.fontSize) && + exactFloatEquality(lhs.fontSizeMultiplier, rhs.fontSizeMultiplier) && + exactFloatEquality(lhs.letterSpacing, rhs.letterSpacing) && exactFloatEquality(lhs.lineHeight, rhs.lineHeight) && + exactFloatEquality(lhs.maxFontSizeMultiplier, rhs.maxFontSizeMultiplier) && lhs.textEffects == rhs.textEffects; } -inline size_t textAttributesHashLayoutWise(const TextAttributes &textAttributes) +namespace detail { + +// Give every NaN one encoding and collapse the signed zeros +inline constexpr auto textCacheFloatBits = [](T value) { + using Bits = std::conditional_t; + static_assert(std::numeric_limits::is_iec559 && (sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t))); + constexpr auto infinity = std::bit_cast(std::numeric_limits::infinity()); + constexpr auto canonicalNaN = std::bit_cast(std::numeric_limits::quiet_NaN()); + const auto bits = std::bit_cast(value); + const auto magnitude = bits << 1; + return magnitude > (infinity << 1) ? canonicalNaN : (magnitude == 0 ? Bits{0} : bits); +}; + +inline void combineTextCacheFloatPair(size_t &seed, Float first, Float second) +{ + const auto firstBits = textCacheFloatBits(first); + const auto secondBits = textCacheFloatBits(second); + if constexpr (sizeof(Float) == sizeof(uint32_t) && sizeof(size_t) == sizeof(uint64_t)) { + const auto pair = (static_cast(firstBits) << 32) | secondBits; + // Fold high bits down at different offsets so power-of-two bucket indexes see both floats + facebook::react::hash_combine(seed, pair ^ (pair >> 16) ^ (pair >> 47)); + } else { + facebook::react::hash_combine(seed, firstBits, secondBits); + } +} + +template +void combineTextCacheOptionals(size_t &seed, const TextAttributes &attributes, const DisplayOptionals &...display) { - // Hash a subset of the attributes compared by `areTextAttributesEquivalentLayoutWise`. - // The optionals are folded into one presence mask rather than being chained individually, so - // that the properties a given text run does not set stay off the hash's dependency chain. This - // is the hot path: it runs on every measurement-cache probe. - size_t seed = 0; - facebook::react::hash_combine( - seed, - textAttributes.fontFamily, - textAttributes.fontSize, - textAttributes.fontSizeMultiplier, - textAttributes.maxFontSizeMultiplier, - textAttributes.letterSpacing, - textAttributes.lineHeight); facebook::react::hash_combine_optionals( seed, - textAttributes.fontWeight, - textAttributes.fontStyle, - textAttributes.fontVariant, - textAttributes.fontVariationSettings, - textAttributes.allowFontScaling, - textAttributes.dynamicTypeRamp, - textAttributes.alignment); + attributes.fontWeight, + attributes.fontStyle, + attributes.fontVariant, + attributes.fontVariationSettings, + attributes.allowFontScaling, + attributes.dynamicTypeRamp, + attributes.alignment, + display...); +} + +template +size_t hashCacheTextAttributes(const TextAttributes &attributes) +{ + auto seed = std::hash{}(attributes.fontFamily); + facebook::react::hash_combine(seed, textCacheFloatBits(attributes.maxFontSizeMultiplier)); + combineTextCacheFloatPair(seed, attributes.fontSize, attributes.fontSizeMultiplier); + combineTextCacheFloatPair(seed, attributes.letterSpacing, attributes.lineHeight); + if constexpr (IncludeDisplayAttributes) { + size_t textEffectsHash = 0; + for (const auto &effect : attributes.textEffects) { + facebook::react::hash_combine(textEffectsHash, effect); + } + facebook::react::hash_combine( + seed, + attributes.foregroundColor, + attributes.backgroundColor, + attributes.textDecorationColor, + attributes.textShadowColor, + textEffectsHash); + combineTextCacheFloatPair(seed, attributes.opacity, attributes.textShadowRadius); + if (attributes.textShadowOffset) { + combineTextCacheFloatPair(seed, attributes.textShadowOffset->width, attributes.textShadowOffset->height); + } + combineTextCacheOptionals( + seed, + attributes, + attributes.textTransform, + attributes.baseWritingDirection, + attributes.lineBreakStrategy, + attributes.lineBreakMode, + attributes.textDecorationLineType, + attributes.textDecorationStyle, + attributes.isHighlighted, + attributes.isPressable, + attributes.layoutDirection, + attributes.accessibilityRole, + attributes.role); + } else { + combineTextCacheOptionals(seed, attributes); + } return seed; } +} // namespace detail + +// Hash a subset of the attributes compared by areTextAttributesEquivalentLayoutWise +inline size_t textAttributesHashLayoutWise(const TextAttributes &attributes) +{ + return detail::hashCacheTextAttributes(attributes); +} + inline bool areAttributedStringFragmentsEquivalentLayoutWise( const AttributedString::Fragment &lhs, const AttributedString::Fragment &rhs) @@ -196,7 +268,7 @@ inline bool areAttributedStringFragmentsEquivalentDisplayWise( const AttributedString::Fragment &lhs, const AttributedString::Fragment &rhs) { - return lhs.isContentEqual(rhs) && + return lhs.string == rhs.string && lhs.textAttributes.equalsForTextCache(rhs.textAttributes) && // LayoutMetrics of an attachment fragment affects the size of a measured // attributed string. (!lhs.isAttachment() || (lhs.parentShadowView.layoutMetrics == rhs.parentShadowView.layoutMetrics)); @@ -207,7 +279,9 @@ inline size_t attributedStringFragmentHashLayoutWise(const AttributedString::Fra // Here we are not taking `isAttachment` and `layoutMetrics` into account // because they are logically interdependent and this can break an invariant // between hash and equivalence functions (and cause cache misses). - return facebook::react::hash_combine(fragment.string, textAttributesHashLayoutWise(fragment.textAttributes)); + auto seed = std::hash{}(fragment.string); + facebook::react::hash_combine(seed, textAttributesHashLayoutWise(fragment.textAttributes)); + return seed; } inline size_t attributedStringFragmentHashDisplayWise(const AttributedString::Fragment &fragment) @@ -215,7 +289,9 @@ inline size_t attributedStringFragmentHashDisplayWise(const AttributedString::Fr // Here we are not taking `isAttachment` and `layoutMetrics` into account // because they are logically interdependent and this can break an invariant // between hash and equivalence functions (and cause cache misses). - return facebook::react::hash_combine(fragment.string, fragment.textAttributes); + auto seed = std::hash{}(fragment.string); + facebook::react::hash_combine(seed, detail::hashCacheTextAttributes(fragment.textAttributes)); + return seed; } inline bool areAttributedStringsEquivalentLayoutWise(const AttributedString &lhs, const AttributedString &rhs) @@ -281,23 +357,41 @@ inline size_t attributedStringHashDisplayWise(const AttributedString &attributed inline bool operator==(const TextMeasureCacheKey &lhs, const TextMeasureCacheKey &rhs) { return areAttributedStringsEquivalentLayoutWise(lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.layoutConstraints == rhs.layoutConstraints && - floatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); + lhs.paragraphAttributes.equalsForTextCache(rhs.paragraphAttributes) && + lhs.layoutConstraints == rhs.layoutConstraints && exactFloatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); } inline bool operator==(const LineMeasureCacheKey &lhs, const LineMeasureCacheKey &rhs) { return areAttributedStringsEquivalentLayoutWise(lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.size == rhs.size; + lhs.paragraphAttributes.equalsForTextCache(rhs.paragraphAttributes) && lhs.size == rhs.size; } inline bool operator==(const PreparedTextCacheKey &lhs, const PreparedTextCacheKey &rhs) { return areAttributedStringsEquivalentDisplayWise(lhs.attributedString, rhs.attributedString) && - lhs.paragraphAttributes == rhs.paragraphAttributes && lhs.layoutConstraints == rhs.layoutConstraints && - floatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); + lhs.paragraphAttributes.equalsForTextCache(rhs.paragraphAttributes) && + lhs.layoutConstraints == rhs.layoutConstraints && exactFloatEquality(lhs.pointScaleFactor, rhs.pointScaleFactor); +} + +namespace detail { + +inline size_t hashConstrainedTextCacheKey( + size_t seed, + const ParagraphAttributes ¶graphAttributes, + const LayoutConstraints &constraints, + Float pointScaleFactor) +{ + facebook::react::hash_combine( + seed, + hashParagraphAttributes(paragraphAttributes, textCacheFloatBits), + constraints, + textCacheFloatBits(pointScaleFactor)); + return seed; } +} // namespace detail + } // namespace facebook::react namespace std { @@ -306,7 +400,7 @@ template <> struct hash { size_t operator()(const facebook::react::TextMeasureCacheKey &key) const { - return facebook::react::hash_combine( + return facebook::react::detail::hashConstrainedTextCacheKey( attributedStringHashLayoutWise(key.attributedString), key.paragraphAttributes, key.layoutConstraints, @@ -319,7 +413,10 @@ struct hash { size_t operator()(const facebook::react::LineMeasureCacheKey &key) const { return facebook::react::hash_combine( - attributedStringHashLayoutWise(key.attributedString), key.paragraphAttributes, key.size); + attributedStringHashLayoutWise(key.attributedString), + facebook::react::detail::hashParagraphAttributes( + key.paragraphAttributes, facebook::react::detail::textCacheFloatBits), + key.size); } }; @@ -327,7 +424,7 @@ template <> struct hash { size_t operator()(const facebook::react::PreparedTextCacheKey &key) const { - return facebook::react::hash_combine( + return facebook::react::detail::hashConstrainedTextCacheKey( attributedStringHashDisplayWise(key.attributedString), key.paragraphAttributes, key.layoutConstraints, diff --git a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/tests/TextLayoutManagerTest.cpp b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/tests/TextLayoutManagerTest.cpp index 512a91e9ff69..79d6b2cb8496 100644 --- a/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/tests/TextLayoutManagerTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/textlayoutmanager/tests/TextLayoutManagerTest.cpp @@ -9,6 +9,8 @@ #include #include +#include +#include #include #include @@ -351,3 +353,151 @@ TEST(TextMeasurementRoundingTest, doesNotInflateHeightWithSubpixelHeadroom) { TEST(TextMeasurementRoundingTest, doesNotInflateWidthWithSubpixelHeadroom) { EXPECT_EQ(widthInPixels(Size{20.1, 100.0}), 61); } + +TEST(TextLayoutManagerTest, cacheKeysDistinguishAdjacentFloatValues) { + AttributedString first; + TextAttributes attributes; + attributes.fontSize = 16; + first.appendFragment({.string = "Text", .textAttributes = attributes}); + auto second = first; + second.getFragments().front().textAttributes.fontSize = + std::nextafter(attributes.fontSize, Float{17}); + + EXPECT_NE( + (TextMeasureCacheKey{.attributedString = first}), + (TextMeasureCacheKey{.attributedString = second})); + EXPECT_NE( + (LineMeasureCacheKey{.attributedString = first}), + (LineMeasureCacheKey{.attributedString = second})); + EXPECT_NE( + (PreparedTextCacheKey{.attributedString = first}), + (PreparedTextCacheKey{.attributedString = second})); + + ParagraphAttributes paragraph; + paragraph.minimumFontSize = 8; + paragraph.minimumFontScale = 0.5; + auto changed = paragraph; + changed.minimumFontSize = std::nextafter(paragraph.minimumFontSize, Float{9}); + EXPECT_NE( + (LineMeasureCacheKey{.paragraphAttributes = paragraph}), + (LineMeasureCacheKey{.paragraphAttributes = changed})); + changed = paragraph; + changed.minimumFontScale = + std::nextafter(paragraph.minimumFontScale, Float{1}); + EXPECT_NE( + (LineMeasureCacheKey{.paragraphAttributes = paragraph}), + (LineMeasureCacheKey{.paragraphAttributes = changed})); + + const auto scale = Float{2}; + const auto nextScale = std::nextafter(scale, Float{3}); + EXPECT_NE( + (TextMeasureCacheKey{.pointScaleFactor = scale}), + (TextMeasureCacheKey{.pointScaleFactor = nextScale})); + EXPECT_NE( + (PreparedTextCacheKey{.pointScaleFactor = scale}), + (PreparedTextCacheKey{.pointScaleFactor = nextScale})); +} + +TEST(TextLayoutManagerTest, cacheKeysHashUnsetFloatRepresentationsEqually) { + const auto expectSameKey = [](const auto& lhs, const auto& rhs) { + using Key = std::decay_t; + EXPECT_EQ(lhs, rhs); + EXPECT_EQ(std::hash{}(lhs), std::hash{}(rhs)); + }; + + for (const auto value : {std::numeric_limits::quiet_NaN(), Float{0}}) { + SCOPED_TRACE(value); + TextAttributes attributes; + attributes.fontSize = value; + AttributedString first; + first.appendFragment({.string = "Text", .textAttributes = attributes}); + auto second = first; + second.getFragments().front().textAttributes.fontSize = -value; + expectSameKey( + TextMeasureCacheKey{.attributedString = first}, + TextMeasureCacheKey{.attributedString = second}); + expectSameKey( + LineMeasureCacheKey{.attributedString = first}, + LineMeasureCacheKey{.attributedString = second}); + expectSameKey( + PreparedTextCacheKey{.attributedString = first}, + PreparedTextCacheKey{.attributedString = second}); + + ParagraphAttributes paragraph; + paragraph.minimumFontScale = value; + auto changed = paragraph; + changed.minimumFontScale = -value; + expectSameKey( + TextMeasureCacheKey{.paragraphAttributes = paragraph}, + TextMeasureCacheKey{.paragraphAttributes = changed}); + expectSameKey( + LineMeasureCacheKey{.paragraphAttributes = paragraph}, + LineMeasureCacheKey{.paragraphAttributes = changed}); + expectSameKey( + PreparedTextCacheKey{.paragraphAttributes = paragraph}, + PreparedTextCacheKey{.paragraphAttributes = changed}); + + expectSameKey( + TextMeasureCacheKey{.pointScaleFactor = value}, + TextMeasureCacheKey{.pointScaleFactor = -value}); + expectSameKey( + PreparedTextCacheKey{.pointScaleFactor = value}, + PreparedTextCacheKey{.pointScaleFactor = -value}); + } +} + +TEST(TextLayoutManagerTest, identicalInfiniteFontLimitsAreReusableCacheKeys) { + ParagraphAttributes paragraph; + paragraph.minimumFontSize = std::numeric_limits::infinity(); + const LineMeasureCacheKey key{.paragraphAttributes = paragraph}; + LineMeasureCache cache{1}; + int measurements = 0; + const auto measure = [&] { + ++measurements; + return LinesMeasurements{}; + }; + + cache.get(key, measure); + cache.get(key, measure); + + EXPECT_EQ(measurements, 1); +} + +TEST(TextLayoutManagerTest, preparedCacheDistinguishesHashedLineBreakModes) { + AttributedString first; + first.appendFragment({.string = "Text"}); + auto second = first; + second.getFragments().front().textAttributes.lineBreakMode = + LineBreakMode::Char; + + EXPECT_FALSE( + (PreparedTextCacheKey{.attributedString = first} == + PreparedTextCacheKey{.attributedString = second})); +} + +TEST(TextLayoutManagerTest, preparedCacheReusesNaNShadowOffsets) { + TextAttributes attributes; + attributes.textShadowOffset = + Size{.width = std::numeric_limits::quiet_NaN(), .height = 1}; + AttributedString text; + text.appendFragment({.string = "Text", .textAttributes = attributes}); + const PreparedTextCacheKey first{.attributedString = text}; + auto second = first; + second.attributedString.getFragments() + .front() + .textAttributes.textShadowOffset->width = + -attributes.textShadowOffset->width; + + EXPECT_EQ(first, second); + EXPECT_EQ( + std::hash{}(first), + std::hash{}(second)); + + SimpleThreadSafeCache cache; + int preparations = 0; + const auto prepare = [&] { return ++preparations; }; + EXPECT_EQ(cache.get(first, prepare), 1); + EXPECT_EQ(cache.get(second, prepare), 1); + EXPECT_EQ(cache.get(PreparedTextCacheKey{}, prepare), 2); + EXPECT_EQ(cache.get(first, prepare), 3); +} diff --git a/packages/react-native/ReactCommon/react/utils/FloatComparison.h b/packages/react-native/ReactCommon/react/utils/FloatComparison.h index 5fc898d1bf8a..0023edf17122 100644 --- a/packages/react-native/ReactCommon/react/utils/FloatComparison.h +++ b/packages/react-native/ReactCommon/react/utils/FloatComparison.h @@ -21,4 +21,11 @@ inline bool floatEquality(T a, T b, T epsilon = static_cast(kDefaultEpsilon)) return (std::isnan(a) && std::isnan(b)) || (!std::isnan(a) && !std::isnan(b) && std::abs(a - b) < epsilon); } +// Compare cache keys exactly, treating NaN as an unset value. +template +inline bool exactFloatEquality(T a, T b) +{ + return a == b || (std::isnan(a) && std::isnan(b)); +} + } // namespace facebook::react diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 4b3d8b0f972b..cfe5e253073f 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -782,7 +782,7 @@ size_t facebook::react::attributedStringFragmentHashDisplayWise(const facebook:: size_t facebook::react::attributedStringFragmentHashLayoutWise(const facebook::react::AttributedString::Fragment& fragment); size_t facebook::react::attributedStringHashDisplayWise(const facebook::react::AttributedString& attributedString); size_t facebook::react::attributedStringHashLayoutWise(const facebook::react::AttributedString& attributedString); -size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& textAttributes); +size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& attributes); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); @@ -856,6 +856,8 @@ T facebook::react::get(const facebook::react::AnimatedPropBase& animatedProp); template T facebook::react::get(const std::unique_ptr& animatedProp); template +bool facebook::react::exactFloatEquality(T a, T b); +template bool facebook::react::floatEquality(T a, T b, T epsilon = static_cast(facebook::react::kDefaultEpsilon)); template folly::dynamic facebook::react::toDynamic(const std::vector& arrayValue); @@ -3145,6 +3147,7 @@ class facebook::react::NativeWebSocketModuleSpecJSI : public facebook::react::Ja class facebook::react::ParagraphAttributes : public facebook::react::DebugStringConvertible { public bool adjustsFontSizeToFit; + public bool equalsForTextCache(const facebook::react::ParagraphAttributes& rhs) const; public bool includeFontPadding; public bool operator==(const facebook::react::ParagraphAttributes& rhs) const; public facebook::react::EllipsizeMode ellipsizeMode; @@ -3942,6 +3945,7 @@ class facebook::react::TelemetryController { } class facebook::react::TextAttributes : public facebook::react::DebugStringConvertible { + public bool equalsForTextCache(const facebook::react::TextAttributes& rhs) const; public bool operator==(const facebook::react::TextAttributes& rhs) const; public facebook::react::Float fontSize; public facebook::react::Float fontSizeMultiplier; @@ -8492,16 +8496,20 @@ void facebook::react::exceptions::throwIfObjectAlreadyConsumed(const T& t, const constexpr auto facebook::react::detail::hexDigits; +constexpr auto facebook::react::detail::textCacheFloatBits; constexpr float facebook::react::detail::hueToRgb(float p, float q, float t); constexpr std::optional facebook::react::detail::normalizeNumberComponent(const std::variant& component); constexpr uint8_t facebook::react::detail::clamp255Component(float f); constexpr uint8_t facebook::react::detail::clampAlpha(std::optional alpha); float facebook::react::detail::normalizeHue(float hue); +size_t facebook::react::detail::hashConstrainedTextCacheKey(size_t seed, const facebook::react::ParagraphAttributes& paragraphAttributes, const facebook::react::LayoutConstraints& constraints, facebook::react::Float pointScaleFactor); std::optional facebook::react::detail::normalizeHueComponent(const std::variant& component); std::tuple facebook::react::detail::hslToRgb(float h, float s, float l); std::tuple facebook::react::detail::hwbToRgb(float h, float w, float b); template constexpr bool facebook::react::detail::isLegacyColorFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashCacheTextAttributes(const facebook::react::TextAttributes& attributes); template constexpr std::optional facebook::react::detail::parseHexDigits(const char* value); template @@ -8518,12 +8526,17 @@ template std::optional facebook::react::detail::parseLegacyHslFunction(facebook::react::CSSValueParser& parser); template std::optional facebook::react::detail::parseModernHslFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashParagraphAttributes(const facebook::react::ParagraphAttributes& attributes, FloatProjection projectFloat); template C facebook::react::detail::memberFunctionClass(T C::*); template void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr, std::weak_ptr) = delete; template constexpr std::optional facebook::react::detail::normalizeComponent(const std::variant& component, float baseValue); +template +void facebook::react::detail::combineTextCacheOptionals(size_t& seed, const facebook::react::TextAttributes& attributes, const DisplayOptionals &... display); +void facebook::react::detail::combineTextCacheFloatPair(size_t& seed, facebook::react::Float first, facebook::react::Float second); void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr object, std::weak_ptr jsInvoker) noexcept; class facebook::react::detail::OwnedBytesBuffer : public facebook::jsi::MutableBuffer { diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index 0bf8e8646dd3..456626c93cd0 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -3535,7 +3535,7 @@ size_t facebook::react::attributedStringFragmentHashDisplayWise(const facebook:: size_t facebook::react::attributedStringFragmentHashLayoutWise(const facebook::react::AttributedString::Fragment& fragment); size_t facebook::react::attributedStringHashDisplayWise(const facebook::react::AttributedString& attributedString); size_t facebook::react::attributedStringHashLayoutWise(const facebook::react::AttributedString& attributedString); -size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& textAttributes); +size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& attributes); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); @@ -3610,6 +3610,8 @@ T facebook::react::get(const facebook::react::AnimatedPropBase& animatedProp); template T facebook::react::get(const std::unique_ptr& animatedProp); template +bool facebook::react::exactFloatEquality(T a, T b); +template bool facebook::react::floatEquality(T a, T b, T epsilon = static_cast(facebook::react::kDefaultEpsilon)); template facebook::react::ModuleConstants facebook::react::typedConstants(typename T::Builder::Input&& value); @@ -5331,6 +5333,7 @@ struct facebook::react::ObjCTurboModule::InitParams { class facebook::react::ParagraphAttributes : public facebook::react::DebugStringConvertible { public bool adjustsFontSizeToFit; + public bool equalsForTextCache(const facebook::react::ParagraphAttributes& rhs) const; public bool includeFontPadding; public bool operator==(const facebook::react::ParagraphAttributes& rhs) const; public facebook::react::EllipsizeMode ellipsizeMode; @@ -6086,6 +6089,7 @@ class facebook::react::TelemetryController { } class facebook::react::TextAttributes : public facebook::react::DebugStringConvertible { + public bool equalsForTextCache(const facebook::react::TextAttributes& rhs) const; public bool operator==(const facebook::react::TextAttributes& rhs) const; public facebook::react::Float fontSize; public facebook::react::Float fontSizeMultiplier; @@ -10346,16 +10350,20 @@ bool facebook::react::HostPlatformViewTraitsInitializer::isKeyboardFocusable(con constexpr auto facebook::react::detail::hexDigits; +constexpr auto facebook::react::detail::textCacheFloatBits; constexpr float facebook::react::detail::hueToRgb(float p, float q, float t); constexpr std::optional facebook::react::detail::normalizeNumberComponent(const std::variant& component); constexpr uint8_t facebook::react::detail::clamp255Component(float f); constexpr uint8_t facebook::react::detail::clampAlpha(std::optional alpha); float facebook::react::detail::normalizeHue(float hue); +size_t facebook::react::detail::hashConstrainedTextCacheKey(size_t seed, const facebook::react::ParagraphAttributes& paragraphAttributes, const facebook::react::LayoutConstraints& constraints, facebook::react::Float pointScaleFactor); std::optional facebook::react::detail::normalizeHueComponent(const std::variant& component); std::tuple facebook::react::detail::hslToRgb(float h, float s, float l); std::tuple facebook::react::detail::hwbToRgb(float h, float w, float b); template constexpr bool facebook::react::detail::isLegacyColorFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashCacheTextAttributes(const facebook::react::TextAttributes& attributes); template constexpr std::optional facebook::react::detail::parseHexDigits(const char* value); template @@ -10372,12 +10380,17 @@ template std::optional facebook::react::detail::parseLegacyHslFunction(facebook::react::CSSValueParser& parser); template std::optional facebook::react::detail::parseModernHslFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashParagraphAttributes(const facebook::react::ParagraphAttributes& attributes, FloatProjection projectFloat); template C facebook::react::detail::memberFunctionClass(T C::*); template void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr, std::weak_ptr) = delete; template constexpr std::optional facebook::react::detail::normalizeComponent(const std::variant& component, float baseValue); +template +void facebook::react::detail::combineTextCacheOptionals(size_t& seed, const facebook::react::TextAttributes& attributes, const DisplayOptionals &... display); +void facebook::react::detail::combineTextCacheFloatPair(size_t& seed, facebook::react::Float first, facebook::react::Float second); void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr object, std::weak_ptr jsInvoker) noexcept; class facebook::react::detail::OwnedBytesBuffer : public facebook::jsi::MutableBuffer { diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index a3424c76afff..11416162fd85 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -353,7 +353,7 @@ size_t facebook::react::attributedStringFragmentHashDisplayWise(const facebook:: size_t facebook::react::attributedStringFragmentHashLayoutWise(const facebook::react::AttributedString::Fragment& fragment); size_t facebook::react::attributedStringHashDisplayWise(const facebook::react::AttributedString& attributedString); size_t facebook::react::attributedStringHashLayoutWise(const facebook::react::AttributedString& attributedString); -size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& textAttributes); +size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& attributes); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); std::optional facebook::react::filterTypeFromString(std::string_view filterName); @@ -426,6 +426,8 @@ T facebook::react::get(const facebook::react::AnimatedPropBase& animatedProp); template T facebook::react::get(const std::unique_ptr& animatedProp); template +bool facebook::react::exactFloatEquality(T a, T b); +template bool facebook::react::floatEquality(T a, T b, T epsilon = static_cast(facebook::react::kDefaultEpsilon)); template void facebook::react::fromRawValue(const facebook::react::PropsParserContext& context, const facebook::react::RawValue& rawValue, T& result, T defaultValue); @@ -1805,6 +1807,7 @@ class facebook::react::ParagraphAttributes : public facebook::react::DebugString public Float minimumFontScale; public Float minimumFontSize; public bool adjustsFontSizeToFit; + public bool equalsForTextCache(const facebook::react::ParagraphAttributes& rhs) const; public bool includeFontPadding; public bool operator==(const facebook::react::ParagraphAttributes& rhs) const; public facebook::react::EllipsizeMode ellipsizeMode; @@ -2470,6 +2473,7 @@ class facebook::react::TextAttributes : public facebook::react::DebugStringConve public Float maxFontSizeMultiplier; public Float opacity; public Float textShadowRadius; + public bool equalsForTextCache(const facebook::react::TextAttributes& rhs) const; public bool operator==(const facebook::react::TextAttributes& rhs) const; public facebook::react::SharedColor backgroundColor; public facebook::react::SharedColor foregroundColor; @@ -5680,16 +5684,20 @@ struct facebook::react::Bridging, std::enable_if_t facebook::react::detail::normalizeNumberComponent(const std::variant& component); constexpr uint8_t facebook::react::detail::clamp255Component(float f); constexpr uint8_t facebook::react::detail::clampAlpha(std::optional alpha); float facebook::react::detail::normalizeHue(float hue); +size_t facebook::react::detail::hashConstrainedTextCacheKey(size_t seed, const facebook::react::ParagraphAttributes& paragraphAttributes, const facebook::react::LayoutConstraints& constraints, Float pointScaleFactor); std::optional facebook::react::detail::normalizeHueComponent(const std::variant& component); std::tuple facebook::react::detail::hslToRgb(float h, float s, float l); std::tuple facebook::react::detail::hwbToRgb(float h, float w, float b); template constexpr bool facebook::react::detail::isLegacyColorFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashCacheTextAttributes(const facebook::react::TextAttributes& attributes); template constexpr std::optional facebook::react::detail::parseHexDigits(const char* value); template @@ -5706,12 +5714,17 @@ template std::optional facebook::react::detail::parseLegacyHslFunction(facebook::react::CSSValueParser& parser); template std::optional facebook::react::detail::parseModernHslFunction(facebook::react::CSSValueParser& parser); +template +size_t facebook::react::detail::hashParagraphAttributes(const facebook::react::ParagraphAttributes& attributes, FloatProjection projectFloat); template C facebook::react::detail::memberFunctionClass(T C::*); template void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr, std::weak_ptr) = delete; template constexpr std::optional facebook::react::detail::normalizeComponent(const std::variant& component, float baseValue); +template +void facebook::react::detail::combineTextCacheOptionals(size_t& seed, const facebook::react::TextAttributes& attributes, const DisplayOptionals &... display); +void facebook::react::detail::combineTextCacheFloatPair(size_t& seed, Float first, Float second); void facebook::react::detail::releaseLongLivedObjectOnJS(std::weak_ptr object, std::weak_ptr jsInvoker) noexcept; class facebook::react::detail::OwnedBytesBuffer : public facebook::jsi::MutableBuffer {