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