RapidFuzz
Loading...
Searching...
No Matches
CharSet.hpp
1/* SPDX-License-Identifier: MIT */
2/* Copyright (c) 2022 Max Bachmann */
3
4#pragma once
5#include <array>
6#include <limits>
7#include <stdint.h>
8#include <stdio.h>
9#include <type_traits>
10#include <unordered_set>
11
12namespace rapidfuzz {
13namespace detail {
14
15/*
16 * taken from https://stackoverflow.com/a/17251989
17 */
18template <typename T, typename U>
19bool CanTypeFitValue(const U value)
20{
21 const intmax_t botT = intmax_t(std::numeric_limits<T>::min());
22 const intmax_t botU = intmax_t(std::numeric_limits<U>::min());
23 const uintmax_t topT = uintmax_t(std::numeric_limits<T>::max());
24 const uintmax_t topU = uintmax_t(std::numeric_limits<U>::max());
25 return !((botT > botU && value < static_cast<U>(botT)) || (topT < topU && value > static_cast<U>(topT)));
26}
27
28template <typename CharT1, size_t size = sizeof(CharT1)>
29struct CharSet;
30
31template <typename CharT1>
32struct CharSet<CharT1, 1> {
33 using UCharT1 = typename std::make_unsigned<CharT1>::type;
34
35 std::array<bool, std::numeric_limits<UCharT1>::max() + 1> m_val;
36
37 CharSet() : m_val{}
38 {}
39
40 void insert(CharT1 ch)
41 {
42 m_val[UCharT1(ch)] = true;
43 }
44
45 template <typename CharT2>
46 bool find(CharT2 ch) const
47 {
48 if (!CanTypeFitValue<CharT1>(ch)) return false;
49
50 return m_val[UCharT1(ch)];
51 }
52};
53
54template <typename CharT1, size_t size>
55struct CharSet {
56 std::unordered_set<CharT1> m_val;
57
58 CharSet() : m_val{}
59 {}
60
61 void insert(CharT1 ch)
62 {
63 m_val.insert(ch);
64 }
65
66 template <typename CharT2>
67 bool find(CharT2 ch) const
68 {
69 if (!CanTypeFitValue<CharT1>(ch)) return false;
70
71 return m_val.find(CharT1(ch)) != m_val.end();
72 }
73};
74
75} // namespace detail
76} // namespace rapidfuzz