// Copyright 2020 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT

#ifndef ZIRCON_KERNEL_LIB_KTL_INCLUDE_CWCHAR
#define ZIRCON_KERNEL_LIB_KTL_INCLUDE_CWCHAR

// The kernel doesn't want this file but some libc++ headers we need
// wind up including it and they need these declarations.

#include <wchar.h>

#include <__config>

_LIBCPP_BEGIN_NAMESPACE_STD

using ::wmemcpy;
using ::wmemmove;
using ::wmemset;

// These are called by libc++ header code.  The first two should never actually
// be called by anything that really gets instantiated in kernel code since
// wchar_t is never used.  However, __constexpr_wmemchr is used by places like
// std::find not just for wchar_t per se but for any trivial type of the same
// size, e.g. uint32_t.  So its code must be correct.  The other two are filled
// out just in case of an unexpected use.

constexpr size_t __constexpr_wcslen(const wchar_t* str) {
  size_t len = 0;
  while (*str++ != L'\0') {
    ++len;
  }
  return len;
}

constexpr int __constexpr_wmemcmp(const wchar_t* lhs, const wchar_t* rhs, size_t count) {
  while (count-- > 0) {
    if (*lhs != *rhs) {
      return static_cast<int>(*lhs - *rhs);
    }
    ++lhs;
    ++rhs;
  }
  return 0;
}

template <class Tp, class Up>
constexpr Tp* __constexpr_wmemchr(Tp* str, Up wc, size_t count) {
  while (count-- > 0) {
    if (*str == wc) {
      return str;
    }
    ++str;
  }
  return nullptr;
}

_LIBCPP_END_NAMESPACE_STD

#endif  // ZIRCON_KERNEL_LIB_KTL_INCLUDE_CWCHAR
