Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: arrayElement overloads failing with non-arithmetic iterators #839

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions include/faker-cxx/helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ T arrayElement(const std::array<T, N>& data)
return data[index];
}

template <std::input_iterator It>
auto arrayElement(It start, It end) -> decltype(*::std::declval<It>())
template <std::random_access_iterator It>
auto arrayElement(It start, It end) -> It::range_difference_t
{
auto size = static_cast<size_t>(end - start);

Expand All @@ -61,7 +61,27 @@ auto arrayElement(It start, It end) -> decltype(*::std::declval<It>())

const std::integral auto index = number::integer<size_t>(size - 1);

return *(start + static_cast<std::iter_difference_t<It>>(index));
return start[index];
}

template <std::input_iterator It>
auto arrayElement(It start, It end)
{
auto size = std::distance(start, end);

if (size == 0)
{
throw std::invalid_argument{"Range [start,end) is empty."};
}

const std::integral auto index = number::integer<size_t>(static_cast<unsigned long>(size - 1));

std::input_iterator auto dummyIterator = start;

for (size_t i = 0; i < index; i++)
dummyIterator++;

return *dummyIterator;
}

/**
Expand Down
7 changes: 4 additions & 3 deletions include/faker-cxx/word.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
#include <optional>
#include <string>
#include <string_view>
#include "faker-cxx/export.h"

#include "faker-cxx/export.h"
#include "faker-cxx/helper.h"

namespace faker::word
Expand Down Expand Up @@ -144,8 +144,9 @@ FAKER_CXX_EXPORT std::string_view preposition(std::optional<unsigned> length = s
*/
FAKER_CXX_EXPORT std::string_view verb(std::optional<unsigned> length = std::nullopt);

template <typename It>
auto sortedSizeArrayElement(std::optional<unsigned int> length, It start, It end) -> decltype(*std::declval<It>())
template <std::input_iterator It>
auto sortedSizeArrayElement(std::optional<unsigned int> length, It start, It end) ->
typename std::iterator_traits<It>::value_type
{
if (!length)
{
Expand Down
Loading