1#include "include/pw.h"
 2#include "src/types/array/array_internal.h"
 3
 4
 5[[nodiscard]] bool indent(PwValuePtr lines, unsigned n, bool rstrip)
 6{
 7    PwValue lines_array = PW_NULL;
 8    PwValuePtr lines_ptr;
 9    if (pw_is_string(lines)) {
10        if (!pw_string_split_chr(lines, '\n', 0, &lines_array)) {
11            return true;
12        }
13        lines_ptr = &lines_array;
14    } else {
15        pw_assert(pw_is_array(lines));
16        lines_ptr = lines;
17    }
18
19    // indent in-place, so access items directly to avoid cloning
20    _PwArray* array = _pw_array_noiter_cow(lines_ptr);
21    if (!array) {
22        return false;
23    }
24
25    unsigned len = pw_array_length(lines_ptr);
26    for (unsigned i = 0; i < len; i++) {
27        PwValuePtr line = &array->items[i];
28        if (rstrip) {
29            if (!pw_string_strip(line)) {
30                return false;
31            }
32        }
33        if (pw_strlen(line)) {
34            if (!pw_string_insert_chars(line, 0, ' ', n)) {
35                return false;
36            }
37        }
38    }
39
40    // pertain the type of result
41    if (pw_is_string(lines)) {
42        if (!pw_array_join(lines_ptr, '\n', lines)) {
43            return false;
44        }
45    }
46    return true;
47}
48
49[[nodiscard]] bool pw_indent(PwValuePtr lines, unsigned n)
50{
51    return indent(lines, n, false);
52}
53
54[[nodiscard]] bool pw_indent_rstrip(PwValuePtr lines, unsigned n)
55{
56    return indent(lines, n, true);
57}