Skip to content

Truly independent web browser

1.5 KB
Raw Blame
/*
 * Copyright (c) 2018-2020, Andreas Kling <[email protected]>
 * Copyright (c) 2021, Tobias Christiansen <[email protected]>
 * Copyright (c) 2021-2023, Sam Atkins <[email protected]>
 * Copyright (c) 2022-2023, MacDue <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "LengthStyleValue.h"

#include <LibWeb/CSS/StyleComputeFFI.h>

namespace Web::CSS {

ValueComparingNonnullRefPtr<LengthStyleValue const> LengthStyleValue::create(Length const& length)
{
    // Small integral pixel lengths dominate real-world values (margins, paddings, borders,
    // font sizes), so they are interned: repeated creations are allocation-free and identical
    // values are pointer-identical.
    static constexpr i32 last_interned_px_value = 64;
    if (length.is_px()) {
        auto raw_value = length.raw_value();
        if (raw_value >= 0 && raw_value <= last_interned_px_value && raw_value == static_cast<i32>(raw_value)) {
            static auto const& instances = *[] {
                auto* instances = new (nothrow) Vector<NonnullRefPtr<LengthStyleValue const>>();
                instances->ensure_capacity(last_interned_px_value + 1);
                for (i32 px = 0; px <= last_interned_px_value; ++px)
                    instances->unchecked_append(*make_immortal(new (nothrow) LengthStyleValue(Length::make_px(px))));
                return instances;
            }();
            return instances[static_cast<i32>(raw_value)];
        }
    }
    return adopt_ref(*new (nothrow) LengthStyleValue(length));
}

}