1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef _LIBCPP___LOCALE_DIR_PAD_AND_OUTPUT_H
10#define _LIBCPP___LOCALE_DIR_PAD_AND_OUTPUT_H
11
12#include <__config>
13
14#if _LIBCPP_HAS_LOCALIZATION
15
16# include <__algorithm/copy.h>
17# include <__algorithm/fill_n.h>
18# include <ios>
19
20# if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
21# pragma GCC system_header
22# endif
23
24_LIBCPP_BEGIN_NAMESPACE_STD
25
26template <class _CharT, class _OutputIterator>
27_LIBCPP_HIDE_FROM_ABI _OutputIterator __pad_and_output(
28 _OutputIterator __s, const _CharT* __ob, const _CharT* __op, const _CharT* __oe, ios_base& __iob, _CharT __fl) {
29 streamsize __sz = __oe - __ob;
30 streamsize __ns = __iob.width();
31 if (__ns > __sz)
32 __ns -= __sz;
33 else
34 __ns = 0;
35 // Explicitly guard against empty outputs (which are expected to be common here) to avoid unconditionally calling
36 // `memmove`/`memset`. See https://llvm.org/PR178685.
37 if (__ob != __op)
38 __s = std::copy(__ob, __op, __s);
39 if (__ns != 0)
40 __s = std::fill_n(__s, __ns, __fl);
41 if (__op != __oe)
42 __s = std::copy(__op, __oe, __s);
43 __iob.width(wide: 0);
44 return __s;
45}
46
47template <class _CharT, class _Traits>
48_LIBCPP_HIDE_FROM_ABI ostreambuf_iterator<_CharT, _Traits> __pad_and_output(
49 ostreambuf_iterator<_CharT, _Traits> __s,
50 const _CharT* __ob,
51 const _CharT* __op,
52 const _CharT* __oe,
53 ios_base& __iob,
54 _CharT __fl) {
55 if (__s.__sbuf_ == nullptr)
56 return __s;
57 streamsize __sz = __oe - __ob;
58 streamsize __ns = __iob.width();
59 if (__ns > __sz)
60 __ns -= __sz;
61 else
62 __ns = 0;
63 __s = std::copy(__ob, __op, __s);
64 if (__ns > 0) {
65 basic_string<_CharT, _Traits> __sp(__ns, __fl);
66 if (__s.__sbuf_->sputn(__sp.data(), __ns) != __ns) {
67 __s.__sbuf_ = nullptr;
68 return __s;
69 }
70 }
71 __s = std::copy(__op, __oe, __s);
72 __iob.width(wide: 0);
73 return __s;
74}
75
76_LIBCPP_END_NAMESPACE_STD
77
78#endif // _LIBCPP_HAS_LOCALIZATION
79
80#endif // _LIBCPP___LOCALE_DIR_PAD_AND_OUTPUT_H
81