Skip to content

Commit

Permalink
Added compat header
Browse files Browse the repository at this point in the history
  • Loading branch information
spoutn1k committed Nov 6, 2021
1 parent c80020f commit fe55715
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 19 deletions.
1 change: 1 addition & 0 deletions src/chunk.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "./chunk.h"
#include <compat.hpp>
#include <functional>

namespace mcmap {
Expand Down
19 changes: 0 additions & 19 deletions src/helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,23 +70,4 @@ fs::path getHome();
fs::path getSaveDir();
fs::path getTempDir();

// TODO Finesse this atrocity out of existence
template <typename F>
typename std::map<int, F>::const_iterator
compatible(const std::map<int, F> &hash, int version) {
auto it = hash.rbegin();
int compatible = 0;

while (it != hash.rend()) {
if (it->first <= version) {
compatible = it->first;
break;
}

it++;
}

return hash.find(compatible);
}

#endif // HELPER_H_
31 changes: 31 additions & 0 deletions src/include/compat.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#pragma once
#include <map>

/* Loosely inspired from lower_bound in
* /usr/include/c++/11.1.0/bits/stl_algobase.h
* Returns a const_iterator to the highest integer that is inferior or equal to
* `version` from the keys of a map<int, F> */
template <typename F>
typename std::map<int, F>::const_iterator
compatible(const std::map<int, F> &hash, int version) {
typedef typename std::map<int, F>::const_iterator _Iterator;
typedef typename _Iterator::difference_type _DistanceType;

_Iterator __first = hash.begin(), __end = hash.end();
_DistanceType __len = std::distance(__first, __end);

while (__len > 1) {
_DistanceType __half = __len >> 1;
_Iterator __middle = __first;
std::advance(__middle, __half);

if (__middle->first > version)
__end = __middle;
else
__first = __middle;

__len = __len - __half;
}

return __first;
}
1 change: 1 addition & 0 deletions src/section.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "./section.h"
#include <compat.hpp>
#include <functional>

namespace versions {
Expand Down
21 changes: 21 additions & 0 deletions tests/test_compat.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <cmath>
#include <compat.hpp>
#include <gtest/gtest.h>

TEST(TestCompat, TestReturn) {
std::map<int, int> versions = {
{0, 0}, {1, 0}, {2, 0}, {4, 0}, {8, 0}, {16, 0},
};

std::map<int, int>::const_iterator it;

it = compatible(versions, 0);
ASSERT_NE(it, versions.end());
ASSERT_EQ(it->first, 0);

for (int i = 1; i < 20; i++) {
it = compatible(versions, i);
ASSERT_NE(it, versions.end());
ASSERT_EQ(it->first, 1 << int(std::log2(double(i))));
}
}

0 comments on commit fe55715

Please sign in to comment.