Avoid potential negative array index access to cached text.
[LibreOffice.git] / vcl / inc / TextLayoutCache.hxx
blob304c6d51ebfb2708c228846077b3db455350b4d5
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #pragma once
22 #include <sal/types.h>
23 #include <rtl/ustring.hxx>
24 #include <o3tl/hash_combine.hxx>
26 #include <vcl/dllapi.h>
28 #include <unicode/uscript.h>
30 #include <vector>
32 namespace vcl::text
34 struct Run
36 int32_t nStart;
37 int32_t nEnd;
38 UScriptCode nCode;
39 Run(int32_t nStart_, int32_t nEnd_, UScriptCode nCode_)
40 : nStart(nStart_)
41 , nEnd(nEnd_)
42 , nCode(nCode_)
47 class VCL_DLLPUBLIC TextLayoutCache
49 public:
50 std::vector<vcl::text::Run> runs;
51 TextLayoutCache(sal_Unicode const* pStr, sal_Int32 const nEnd);
52 // Creates a cached instance.
53 static std::shared_ptr<const vcl::text::TextLayoutCache> Create(OUString const&);
56 struct FirstCharsStringHash
58 size_t operator()(const OUString& str) const
60 // Strings passed to GenericSalLayout::CreateTextLayoutCache() may be very long,
61 // and computing an entire hash could almost negate the gain of hashing. Hash just first
62 // characters, that should be good enough.
63 size_t hash
64 = rtl_ustr_hashCode_WithLength(str.getStr(), std::min<size_t>(100, str.getLength()));
65 o3tl::hash_combine(hash, str.getLength());
66 return hash;
70 struct FastStringCompareEqual
72 bool operator()(const OUString& str1, const OUString& str2) const
74 // Strings passed to GenericSalLayout::CreateTextLayoutCache() may be very long,
75 // and OUString operator == compares backwards and using hard-written code, while
76 // memcmp() compares much faster.
77 if (str1.getLength() != str2.getLength())
78 return false;
79 if (str1.getStr() == str2.getStr())
80 return true;
81 return memcmp(str1.getStr(), str2.getStr(), str1.getLength() * sizeof(str1.getStr()[0]))
82 == 0;
87 /* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */