xrpld
Loading...
Searching...
No Matches
join.h
1#pragma once
2
3#include <cstddef>
4#include <string>
5#include <string_view>
6#include <utility>
7
8namespace xrpl {
9
10template <class Stream, class Iter>
11Stream&
12join(Stream& s, Iter iter, Iter end, std::string_view delimiter)
13{
14 if (iter == end)
15 return s;
16 s << *iter;
17 for (++iter; iter != end; ++iter)
18 s << delimiter << *iter;
19 return s;
20}
21
22template <class Collection>
24{
25public:
26 Collection const& collection;
28
29 explicit CollectionAndDelimiter(Collection const& c, std::string delim)
30 : collection(c), delimiter(std::move(delim))
31 {
32 }
33
34 template <class Stream>
35 friend Stream&
36 operator<<(Stream& s, CollectionAndDelimiter const& cd)
37 {
38 return join(s, std::begin(cd.collection), std::end(cd.collection), cd.delimiter);
39 }
40};
41
42template <class Collection, std::size_t N>
43class CollectionAndDelimiter<Collection[N]>
44{
45public:
46 Collection const* collection;
48
49 explicit CollectionAndDelimiter(Collection const c[N], std::string delim)
50 : collection(c), delimiter(std::move(delim))
51 {
52 }
53
54 template <class Stream>
55 friend Stream&
56 operator<<(Stream& s, CollectionAndDelimiter const& cd)
57 {
58 return join(s, cd.collection, cd.collection + N, cd.delimiter);
59 }
60};
61
62// Specialization for const char* strings
63template <std::size_t N>
65{
66public:
67 char const* collection;
69
70 explicit CollectionAndDelimiter(char const c[N], std::string delim)
71 : collection(c), delimiter(std::move(delim))
72 {
73 }
74
75 template <class Stream>
76 friend Stream&
77 operator<<(Stream& s, CollectionAndDelimiter const& cd)
78 {
79 auto end = cd.collection + N;
80 if (N > 0 && *(end - 1) == '\0')
81 --end;
82 return join(s, cd.collection, end, cd.delimiter);
83 }
84};
85
86} // namespace xrpl
T begin(T... args)
CollectionAndDelimiter(Collection const c[N], std::string delim)
Definition join.h:49
CollectionAndDelimiter(char const c[N], std::string delim)
Definition join.h:70
friend Stream & operator<<(Stream &s, CollectionAndDelimiter const &cd)
Definition join.h:36
Collection const & collection
Definition join.h:26
std::string const delimiter
Definition join.h:27
CollectionAndDelimiter(Collection const &c, std::string delim)
Definition join.h:29
T end(T... args)
STL namespace.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
Stream & join(Stream &s, Iter iter, Iter end, std::string_view delimiter)
Definition join.h:12