// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/uuid.h"

#include <stddef.h>
#include <stdint.h>

#include <ostream>
#include <string_view>

#include "base/check.h"
#include "base/compiler_specific.h"
#include "base/containers/span.h"
#include "base/hash/hash.h"
#include "base/numerics/byte_conversions.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/types/pass_key.h"
#include "third_party/abseil-cpp/absl/numeric/int128.h"

namespace base {

namespace {

template <typename Char>
constexpr bool IsLowerHexDigit(Char c) {
  return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
}

constexpr bool IsHyphenPosition(size_t i) {
  return i == 8 || i == 13 || i == 18 || i == 23;
}

// Returns a canonical Uuid string given that `input` is validly formatted
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, such that x is a hexadecimal digit.
// If `strict`, x must be a lower-case hexadecimal digit.
template <typename StringPieceType>
std::string GetCanonicalUuidInternal(StringPieceType input, bool strict) {
  using CharType = typename StringPieceType::value_type;

  constexpr size_t kUuidLength = 36;
  if (input.length() != kUuidLength) {
    return std::string();
  }

  std::string lowercase_;
  lowercase_.resize(kUuidLength);
  for (size_t i = 0; i < input.length(); ++i) {
    CharType current = input[i];
    if (IsHyphenPosition(i)) {
      if (current != '-') {
        return std::string();
      }
      lowercase_[i] = '-';
    } else {
      if (strict ? !IsLowerHexDigit(current) : !IsHexDigit(current)) {
        return std::string();
      }
      lowercase_[i] = static_cast<char>(ToLowerASCII(current));
    }
  }

  return lowercase_;
}

}  // namespace

// static
Uuid Uuid::GenerateRandomV4() {
  uint8_t sixteen_bytes[kGuidV4InputLength];
  // Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
  // base version directly, and to prevent the dependency from base/ to crypto/.
  RandBytes(sixteen_bytes);
  return FormatRandomDataAsV4Impl(sixteen_bytes);
}

// static
Uuid Uuid::FormatRandomDataAsV4Impl(base::span<const uint8_t, 16> input) {
  DCHECK_EQ(input.size_bytes(), kGuidV4InputLength);

  uint64_t first_u64 = U64FromLittleEndian(input.first<8>());
  uint64_t second_u64 = U64FromLittleEndian(input.last<8>());

  // Set the Uuid to version 4 as described in RFC 4122, section 4.4.
  // The format of Uuid version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
  // where y is one of [8, 9, a, b].

  // Clear the version bits and set the version to 4:
  first_u64 &= 0xffffffff'ffff0fffULL;
  first_u64 |= 0x00000000'00004000ULL;

  // Clear bit 65 and set bit 64, to set the 'var' field to 0b10 per RFC 9562
  // section 5.4.
  second_u64 &= 0x3fffffff'ffffffffULL;
  second_u64 |= 0x80000000'00000000ULL;

  Uuid uuid;
  uuid.lowercase_ = StringPrintf(
      "%08x-%04x-%04x-%04x-%012llx", static_cast<uint32_t>(first_u64 >> 32),
      static_cast<uint32_t>((first_u64 >> 16) & 0x0000ffff),
      static_cast<uint32_t>(first_u64 & 0x0000ffff),
      static_cast<uint32_t>(second_u64 >> 48),
      second_u64 & 0x0000ffff'ffffffffULL);
  return uuid;
}

// static
Uuid Uuid::ParseCaseInsensitive(std::string_view input) {
  Uuid uuid;
  uuid.lowercase_ = GetCanonicalUuidInternal(input, /*strict=*/false);
  return uuid;
}

// static
Uuid Uuid::ParseCaseInsensitive(std::u16string_view input) {
  Uuid uuid;
  uuid.lowercase_ = GetCanonicalUuidInternal(input, /*strict=*/false);
  return uuid;
}

// static
Uuid Uuid::ParseLowercase(std::string_view input) {
  Uuid uuid;
  uuid.lowercase_ = GetCanonicalUuidInternal(input, /*strict=*/true);
  return uuid;
}

// static
Uuid Uuid::ParseLowercase(std::u16string_view input) {
  Uuid uuid;
  uuid.lowercase_ = GetCanonicalUuidInternal(input, /*strict=*/true);
  return uuid;
}

Uuid::Uuid() = default;

Uuid::Uuid(const Uuid& other) = default;

Uuid& Uuid::operator=(const Uuid& other) = default;

Uuid::Uuid(Uuid&& other) = default;

Uuid& Uuid::operator=(Uuid&& other) = default;

const std::string& Uuid::AsLowercaseString() const {
  return lowercase_;
}

absl::uint128 Uuid::AsInteger() const {
  if (!is_valid()) {
    return 0;
  }
  // Valid Uuids have the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where x is
  // a hexadecimal digit.
  // Convert each dash-separated part into an integer and combine the results.
  std::string_view uuid = lowercase_;
  uint64_t p0, p1, p2, p3, p4;
  CHECK(base::HexStringToUInt64(uuid.substr(0, 8), &p0));
  CHECK(base::HexStringToUInt64(uuid.substr(9, 4), &p1));
  CHECK(base::HexStringToUInt64(uuid.substr(14, 4), &p2));
  CHECK(base::HexStringToUInt64(uuid.substr(19, 4), &p3));
  CHECK(base::HexStringToUInt64(uuid.substr(24, 12), &p4));
  uint64_t most_significant_bits = (p0 << 32) | (p1 << 16) | p2;
  uint64_t least_significant_bits = (p3 << 48) | p4;
  return absl::MakeUint128(most_significant_bits, least_significant_bits);
}

std::ostream& operator<<(std::ostream& out, const Uuid& uuid) {
  return out << uuid.AsLowercaseString();
}

size_t UuidHash::operator()(const Uuid& uuid) const {
  // TODO(crbug.com/40108138): Avoid converting to string to take the hash when
  // the internal type is migrated to a non-string type.
  return FastHash(uuid.AsLowercaseString());
}

}  // namespace base
