summaryrefslogtreecommitdiff
path: root/asl/string_builder.hpp
blob: 378ec487da6456aadc8cbad46826a51a245c4d6c (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once

#include "asl/buffer.hpp"
#include "asl/string.hpp"
#include "asl/string_view.hpp"

namespace asl
{

template<allocator Allocator = DefaultAllocator>
class string_builder
{
    buffer<char, Allocator> m_buffer;

public:
    constexpr string_builder() requires default_constructible<Allocator> = default;
    explicit constexpr string_builder(Allocator allocator) : m_buffer{ASL_MOVE(allocator)} {}

    constexpr ~string_builder() = default;

    constexpr string_builder(const string_builder&) requires copy_constructible<Allocator> = default;
    constexpr string_builder(string_builder&&) = default;

    constexpr string_builder& operator=(const string_builder&) requires copy_assignable<Allocator> = default;
    constexpr string_builder& operator=(string_builder&&) = default;

    constexpr string_view as_string_view() const
    {
        auto span = m_buffer.as_span();
        return string_view{span.data(), span.size()};
    }

    void reset()
    {
        m_buffer.clear();
    }

    // @Todo(C++23) Deducing this

    string_builder& push(string_view sv) &
    {
        isize_t old_size = m_buffer.size();
        m_buffer.resize_zero(old_size + sv.size());
        asl::memcpy(m_buffer.data() + old_size, sv.data(), sv.size());
        return *this;
    }

    string_builder&& push(string_view sv) &&
    {
        isize_t old_size = m_buffer.size();
        m_buffer.resize_zero(old_size + sv.size());
        asl::memcpy(m_buffer.data() + old_size, sv.data(), sv.size());
        return ASL_MOVE(*this);
    }

    string_builder& push(char c) &
    {
        m_buffer.push(c);
        return *this;
    }

    string_builder&& push(char c) &&
    {
        m_buffer.push(c);
        return ASL_MOVE(*this);
    }

    string<Allocator> finish() &&
    {
        return string<Allocator>{ASL_MOVE(m_buffer)};
    }

    template<allocator StringAllocator = Allocator>
    string<StringAllocator> as_string()
        requires default_constructible<StringAllocator>
    {
        return string<StringAllocator>{as_string_view()};
    }

    template<allocator StringAllocator = Allocator>
    string<StringAllocator> as_string(Allocator allocator)
    {
        return string<StringAllocator>{as_string_view(), ASL_MOVE(allocator)};
    }
};

string_builder() -> string_builder<>;

} // namespace asl