aboutsummaryrefslogtreecommitdiff
path: root/libc/src/wchar/wcstok.cpp
blob: ed4f0aad08ea53e3ec4c1df06a4508c3c98a5348 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//===-- Implementation of wcstok ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "src/wchar/wcstok.h"

#include "hdr/types/wchar_t.h"
#include "src/__support/common.h"
#include "wchar_utils.h"

namespace LIBC_NAMESPACE_DECL {

LLVM_LIBC_FUNCTION(wchar_t *, wcstok,
                   (wchar_t *__restrict str, const wchar_t *__restrict delims,
                    wchar_t **__restrict context)) {
  if (str == nullptr) {
    if (*context == nullptr)
      return nullptr;

    str = *context;
  }

  wchar_t *tok_start = str;
  while (*tok_start != L'\0' && internal::wcschr(delims, *tok_start))
    ++tok_start;

  wchar_t *tok_end = tok_start;
  while (*tok_end != L'\0' && !internal::wcschr(delims, *tok_end))
    ++tok_end;

  if (*tok_end != L'\0') {
    *tok_end = L'\0';
    ++tok_end;
  }
  *context = tok_end;
  return *tok_start == L'\0' ? nullptr : tok_start;
}

} // namespace LIBC_NAMESPACE_DECL