xref: /aosp_15_r20/external/skia/tests/SkFontMetricsPrivTest.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2023 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/core/SkFontMetricsPriv.h"
9 
10 #include "include/core/SkFont.h"
11 #include "include/core/SkFontMetrics.h"
12 #include "include/core/SkTypeface.h"
13 #include "src/core/SkReadBuffer.h"
14 #include "src/core/SkScalerContext.h"
15 #include "src/core/SkStrikeSpec.h"
16 #include "src/core/SkWriteBuffer.h"
17 #include "tests/Test.h"
18 #include "tools/fonts/FontToolUtils.h"
19 
20 #include <optional>
21 
DEF_TEST(SkFontMetricsPriv_Basic,reporter)22 DEF_TEST(SkFontMetricsPriv_Basic, reporter) {
23     auto typeface = ToolUtils::CreateTestTypeface("monospace", SkFontStyle());
24     SkFont font{typeface};
25     SkStrikeSpec spec = SkStrikeSpec::MakeWithNoDevice(font);
26     auto context = spec.createScalerContext();
27     SkFontMetrics srcMetrics;
28 
29     // Check that font metrics round-trip.
30     context->getFontMetrics(&srcMetrics);
31 
32     SkBinaryWriteBuffer writeBuffer({});
33     SkFontMetricsPriv::Flatten(writeBuffer, srcMetrics);
34 
35     auto data = writeBuffer.snapshotAsData();
36 
37     SkReadBuffer readBuffer{data->data(), data->size()};
38 
39     std::optional<SkFontMetrics> dstMetrics = SkFontMetricsPriv::MakeFromBuffer(readBuffer);
40 
41     REPORTER_ASSERT(reporter, dstMetrics.has_value());
42     REPORTER_ASSERT(reporter, srcMetrics == dstMetrics.value());
43 
44     // Check that a broken buffer is detected.
45     // Must be multiple of 4 for a valid buffer.
46     std::uint8_t brokenData[] = {1, 2, 3, 4, 5, 6, 7, 8};
47     SkReadBuffer brokenBuffer{brokenData, std::size(brokenData)};
48 
49     dstMetrics = SkFontMetricsPriv::MakeFromBuffer(brokenBuffer);
50     REPORTER_ASSERT(reporter, !dstMetrics.has_value());
51 }
52 
53 
54