Skip to content

Commit

Permalink
util: move HasPrefix() so it can be reused
Browse files Browse the repository at this point in the history
Move the function `HasPrefix()` from `netaddress.cpp` to `util/string.h`
so it can be reused by `CNetAddr` methods (and possibly others).
  • Loading branch information
vasild authored and furszy committed Aug 10, 2021
1 parent f6f86af commit d41adb4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
12 changes: 3 additions & 9 deletions src/netaddress.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

#include "netaddress.h"
#include "hash.h"
#include "utilstrencodings.h"
#include "util/asmap.h"
#include "tinyformat.h"
#include "util/asmap.h"
#include "util/string.h"
#include "utilstrencodings.h"

#include <algorithm>
#include <array>
Expand Down Expand Up @@ -50,13 +51,6 @@ void CNetAddr::SetIP(const CNetAddr& ipIn)
m_addr = ipIn.m_addr;
}

template <typename T1, size_t PREFIX_LEN>
inline bool HasPrefix(const T1& obj, const std::array<uint8_t, PREFIX_LEN>& prefix)
{
return obj.size() >= PREFIX_LEN &&
std::equal(std::begin(prefix), std::end(prefix), std::begin(obj));
}

void CNetAddr::SetLegacyIPv6(Span<const uint8_t> ipv6)
{
assert(ipv6.size() == ADDR_IPV6_SIZE);
Expand Down
15 changes: 15 additions & 0 deletions src/util/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
#ifndef BITCOIN_UTIL_STRING_H
#define BITCOIN_UTIL_STRING_H

#include "attributes.h"

#include <algorithm>
#include <array>
#include <cstring>
#include <functional>
#include <string>
Expand Down Expand Up @@ -41,4 +45,15 @@ inline bool ValidAsCString(const std::string& str) noexcept
return str.size() == strlen(str.c_str());
}

/**
* Check whether a container begins with the given prefix.
*/
template <typename T1, size_t PREFIX_LEN>
NODISCARD inline bool HasPrefix(const T1& obj,
const std::array<uint8_t, PREFIX_LEN>& prefix)
{
return obj.size() >= PREFIX_LEN &&
std::equal(std::begin(prefix), std::end(prefix), std::begin(obj));
}

#endif // BITCOIN_UTIL_STRENCODINGS_H

0 comments on commit d41adb4

Please sign in to comment.