test-smi-lexicographic-compare.cc 1.96 KB
Newer Older
1 2 3 4 5 6
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>

7
#include "src/init/v8.h"
8
#include "src/objects/objects-inl.h"
9
#include "src/objects/smi.h"
10 11 12 13 14 15 16
#include "test/cctest/cctest.h"

namespace v8 {
namespace internal {

namespace {

17
void AddSigned(std::set<Smi>* smis, int64_t x) {
18 19
  if (!Smi::IsValid(x)) return;

20 21
  smis->insert(Smi::FromInt(static_cast<int>(x)));
  smis->insert(Smi::FromInt(static_cast<int>(-x)));
22 23 24
}

// Uses std::lexicographical_compare twice to convert the result to -1, 0 or 1.
25
int ExpectedCompareResult(Smi a, Smi b) {
26 27
  std::string str_a = std::to_string(a.value());
  std::string str_b = std::to_string(b.value());
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  bool expected_a_lt_b = std::lexicographical_compare(
      str_a.begin(), str_a.end(), str_b.begin(), str_b.end());
  bool expected_b_lt_a = std::lexicographical_compare(
      str_b.begin(), str_b.end(), str_a.begin(), str_a.end());

  if (!expected_a_lt_b && !expected_b_lt_a) {
    return 0;
  } else if (expected_a_lt_b) {
    return -1;
  } else {
    CHECK(expected_b_lt_a);
    return 1;
  }
}

43 44
bool Test(Isolate* isolate, Smi a, Smi b) {
  int actual = Smi(Smi::LexicographicCompare(isolate, a, b)).value();
45 46 47 48 49 50 51 52 53 54 55
  int expected = ExpectedCompareResult(a, b);

  return actual == expected;
}

}  // namespace

TEST(TestSmiLexicographicCompare) {
  Isolate* isolate = CcTest::InitIsolateOnce();
  HandleScope scope(isolate);

56
  std::set<Smi> smis;
57 58 59 60

  for (int64_t xb = 1; xb <= Smi::kMaxValue; xb *= 10) {
    for (int64_t xf = 0; xf <= 9; ++xf) {
      for (int64_t xo = -1; xo <= 1; ++xo) {
61
        AddSigned(&smis, xb * xf + xo);
62 63 64 65 66 67
      }
    }
  }

  for (int64_t yb = 1; yb <= Smi::kMaxValue; yb *= 2) {
    for (int64_t yo = -2; yo <= 2; ++yo) {
68
      AddSigned(&smis, yb + yo);
69 70 71
    }
  }

72 73
  for (Smi a : smis) {
    for (Smi b : smis) {
74 75 76 77 78 79 80
      CHECK(Test(isolate, a, b));
    }
  }
}

}  // namespace internal
}  // namespace v8