srctree

Robin Linden parent d427090a 9c4220f6
type: Add a 'naive' text-measurement implementation

This does the exact thing we're doing in //layout already.

inlinesplit
type/BUILD added: 102, removed: 4, total 98
@@ -1,4 +1,4 @@
load("@rules_cc//cc:defs.bzl", "cc_library")
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//bzl:copts.bzl", "HASTUR_COPTS")
 
cc_library(
@@ -7,3 +7,22 @@ cc_library(
copts = HASTUR_COPTS,
visibility = ["//visibility:public"],
)
 
cc_library(
name = "naive",
hdrs = ["naive.h"],
copts = HASTUR_COPTS,
visibility = ["//visibility:public"],
deps = [":type"],
)
 
cc_test(
name = "naive_test",
size = "small",
srcs = ["naive_test.cpp"],
copts = HASTUR_COPTS,
deps = [
":naive",
"//etest",
],
)
 
filename was Deleted added: 102, removed: 4, total 98
@@ -0,0 +1,46 @@
// SPDX-FileCopyrightText: 2023 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
 
#ifndef TYPE_NAIVE_H_
#define TYPE_NAIVE_H_
 
#include "type/type.h"
 
#include <map>
#include <memory>
#include <optional>
#include <string_view>
#include <utility>
 
namespace type {
 
class NaiveFont : public IFont {
public:
explicit NaiveFont(Px font_size) : font_size_{font_size} {}
 
Size measure(std::string_view text) const override {
return Size{static_cast<int>(text.size()) * font_size_.v / 2, font_size_.v};
}
 
private:
Px font_size_{};
};
 
class NaiveType : public IType {
public:
std::optional<std::shared_ptr<IFont const>> font(std::string_view, Px size) const override {
if (auto font = font_cache_.find(size.v); font != font_cache_.end()) {
return font->second;
}
 
return font_cache_.insert(std::pair{size.v, std::make_shared<NaiveFont>(size)}).first->second;
}
 
private:
mutable std::map<int, std::shared_ptr<NaiveFont>> font_cache_;
};
 
} // namespace type
 
#endif
 
filename was Deleted added: 102, removed: 4, total 98
@@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: 2023 Robin Lindén <dev@robinlinden.eu>
//
// SPDX-License-Identifier: BSD-2-Clause
 
#include "type/naive.h"
 
#include "etest/etest2.h"
 
int main() {
etest::Suite s{"type/naive"};
 
s.add_test("NaiveFont::measure", [](etest::IActions &a) {
type::NaiveType type{};
 
auto font10px = type.font("a", type::Px{10}).value();
a.expect_eq(font10px->measure("a"), type::Size{5, 10});
a.expect_eq(font10px->measure("hello"), type::Size{25, 10});
 
auto font20px = type.font("a", type::Px{20}).value();
a.expect_eq(font20px->measure("a"), type::Size{10, 20});
a.expect_eq(font20px->measure("hello"), type::Size{50, 20});
});
 
s.add_test("NaiveType::font_cache", [](etest::IActions &a) {
type::NaiveType type{};
 
auto font0 = type.font("a", type::Px{10}).value();
auto font1 = type.font("a", type::Px{10}).value();
a.expect_eq(font0.get(), font1.get());
});
 
return s.run();
}