KContacts

addressformatparser.cpp
1/*
2 SPDX-FileCopyrightText: 2022 Volker Krause <vkrause@kde.org>
3 SPDX-License-Identifier: LGPL-2.0-or-later
4*/
5
6#include "addressformat_p.h"
7#include "addressformatparser_p.h"
8
9#include <QDebug>
10
11using namespace KContacts;
12
13struct {
14 char c;
16} static constexpr const field_map[] = {
17 {'A', AddressFormatField::StreetAddress},
18 {'C', AddressFormatField::Locality},
19 {'D', AddressFormatField::DependentLocality},
20 {'N', AddressFormatField::Name},
21 {'O', AddressFormatField::Organization},
22 {'P', AddressFormatField::PostOfficeBox},
23 {'R', AddressFormatField::Country},
24 {'S', AddressFormatField::Region},
25 {'X', AddressFormatField::SortingCode},
26 {'Z', AddressFormatField::PostalCode},
27};
28
29AddressFormatField AddressFormatParser::parseField(QChar c)
30{
31 const auto it = std::lower_bound(std::begin(field_map), std::end(field_map), c.cell(), [](auto lhs, auto rhs) {
32 return lhs.c < rhs;
33 });
34 if (it == std::end(field_map) || (*it).c != c.cell() || c.row() != 0) {
35 return AddressFormatField::NoField;
36 }
37 return (*it).f;
38}
39
40AddressFormatFields AddressFormatParser::parseFields(QStringView s)
41{
43 for (auto c : s) {
44 fields |= parseField(c);
45 }
46 return fields;
47}
48
49std::vector<AddressFormatElement> AddressFormatParser::parseElements(QStringView s)
50{
51 std::vector<AddressFormatElement> elements;
52 QString literal;
53 for (auto it = s.begin(); it != s.end(); ++it) {
54 if ((*it) == QLatin1Char('%') && std::next(it) != s.end()) {
55 if (!literal.isEmpty()) {
57 auto e = AddressFormatElementPrivate::get(elem);
58 e->literal = std::move(literal);
59 elements.push_back(elem);
60 }
61 ++it;
62 if ((*it) == QLatin1Char('n')) {
63 elements.push_back(AddressFormatElement{});
64 } else {
65 const auto f = parseField(*it);
66 if (f == AddressFormatField::NoField) {
67 qWarning() << "invalid format field element: %" << *it << "in" << s;
68 } else {
70 auto e = AddressFormatElementPrivate::get(elem);
71 e->field = f;
72 elements.push_back(elem);
73 }
74 }
75 } else {
76 literal.push_back(*it);
77 }
78 }
79 if (!literal.isEmpty()) {
81 auto e = AddressFormatElementPrivate::get(elem);
82 e->literal = std::move(literal);
83 elements.push_back(elem);
84 }
85 return elements;
86}
A single element in an address format.
AddressFormatField
Address field types.
Definition namespace.h:44
bool isEmpty() const const
void push_back(QChar ch)
const_iterator begin() const const
const_iterator end() const const
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri Nov 22 2024 12:06:34 by doxygen 1.12.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.