/src/serenity/Userland/Libraries/LibSQL/ResultSet.cpp
Line | Count | Source |
1 | | /* |
2 | | * Copyright (c) 2022, Jan de Visser <jan@de-visser.net> |
3 | | * |
4 | | * SPDX-License-Identifier: BSD-2-Clause |
5 | | */ |
6 | | |
7 | | #include <LibSQL/ResultSet.h> |
8 | | |
9 | | namespace SQL { |
10 | | |
11 | | size_t ResultSet::binary_search(Tuple const& sort_key, size_t low, size_t high) |
12 | 0 | { |
13 | 0 | if (high <= low) { |
14 | 0 | auto compare = sort_key.compare(at(low).sort_key); |
15 | 0 | return (compare > 0) ? low + 1 : low; |
16 | 0 | } |
17 | | |
18 | 0 | auto mid = (low + high) / 2; |
19 | 0 | auto compare = sort_key.compare(at(mid).sort_key); |
20 | 0 | if (compare == 0) |
21 | 0 | return mid + 1; |
22 | | |
23 | 0 | if (compare > 0) |
24 | 0 | return binary_search(sort_key, mid + 1, high); |
25 | 0 | return binary_search(sort_key, low, mid); |
26 | 0 | } |
27 | | |
28 | | void ResultSet::insert_row(Tuple const& row, Tuple const& sort_key) |
29 | 0 | { |
30 | 0 | if ((sort_key.size() == 0) || is_empty()) { |
31 | 0 | empend(row, sort_key); |
32 | 0 | return; |
33 | 0 | } |
34 | 0 | auto ix = binary_search(sort_key, 0, size() - 1); |
35 | 0 | insert(ix, ResultRow { row, sort_key }); |
36 | 0 | } |
37 | | |
38 | | void ResultSet::limit(size_t offset, size_t limit) |
39 | 0 | { |
40 | 0 | if (offset > 0) { |
41 | 0 | if (offset > size()) { |
42 | 0 | clear(); |
43 | 0 | return; |
44 | 0 | } |
45 | | |
46 | 0 | remove(0, offset); |
47 | 0 | } |
48 | | |
49 | 0 | if (size() > limit) |
50 | 0 | remove(limit, size() - limit); |
51 | 0 | } |
52 | | |
53 | | } |