KItinerary

alphaid.h
1 /*
2  SPDX-FileCopyrightText: 2019 Volker Krause <[email protected]>
3 
4  SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6 
7 #ifndef KITINERARY_KNOWLEDGEDB_ALPHAID_H
8 #define KITINERARY_KNOWLEDGEDB_ALPHAID_H
9 
10 #include "kitinerary_export.h"
11 
12 #include <QDebug>
13 #include <QString>
14 
15 #include <cstdint>
16 
17 namespace KItinerary {
18 namespace KnowledgeDb {
19 
21 namespace Internal {
22  // "private" API for the template code below
23  KITINERARY_EXPORT uint16_t alphaIdFromString(const QString &s, int size);
24  KITINERARY_EXPORT QString alphaIdToString(uint16_t id, int size);
25 }
27 
32 template <typename T, int N>
33 class AlphaId {
34  static_assert((N * 5) < (sizeof(T) * 8), "Not enough space to hold identifier.");
35 public:
36  inline constexpr AlphaId() = default;
38  inline explicit constexpr AlphaId(const char s[N])
39  {
40  for (int i = 0; i < N; ++i) {
41  if (s[i] < 'A' || s[i] > 'Z') {
42  m_id = {};
43  return;
44  }
45  m_id |= (s[i] - '@') << (5 * (N-i-1));
46  }
47  }
49  inline explicit AlphaId(const QString &s)
50  {
51  static_assert(sizeof(decltype(Internal::alphaIdFromString(s, N))) <= sizeof(T), "alphaIdFromString truncates result");
52  m_id = Internal::alphaIdFromString(s, N);
53  }
54 
56  inline constexpr bool isValid() const
57  {
58  return m_id != 0;
59  }
60 
61  inline constexpr bool operator<(AlphaId<T, N> rhs) const
62  {
63  return m_id < rhs.m_id;
64  }
65  inline constexpr bool operator==(AlphaId<T, N> other) const
66  {
67  return m_id == other.m_id;
68  }
69  inline constexpr bool operator!=(AlphaId<T, N> other) const
70  {
71  return m_id != other.m_id;
72  }
73 
75  inline QString toString() const
76  {
77  return Internal::alphaIdToString(m_id, N);
78  }
79 
80 private:
81  T m_id = {};
82 };
83 
84 }
85 
86 }
87 
88 template <typename T, int N>
89 inline QDebug operator<<(QDebug dbg, KItinerary::KnowledgeDb::AlphaId<T, N> id)
90 {
91  dbg << id.toString();
92  return dbg;
93 }
94 
95 #endif // KITINERARY_KNOWLEDGEDB_ALPHAID_H
constexpr bool isValid() const
Returns true if this is a valid idenfier.
Definition: alphaid.h:56
Classes for reservation/travel data models, data extraction and data augmentation.
QString toString() const
Returns a string representation of this identifier.
Definition: alphaid.h:75
constexpr AlphaId(const char s[N])
Create identifier from a literal.
Definition: alphaid.h:38
AlphaId(const QString &s)
Create identifier from a QString.
Definition: alphaid.h:49
Compact storage for fixed-size identifiers consisting out of uppercase latin letters, such as IATA airport codes or ISO 3166 country codes.
Definition: alphaid.h:33
This file is part of the KDE documentation.
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sat Aug 8 2020 23:11:56 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.