1#include "duckdb/function/scalar/string_functions.hpp"
2
3#include "duckdb/common/exception.hpp"
4#include "duckdb/common/vector_operations/vector_operations.hpp"
5#include "duckdb/common/vector_operations/unary_executor.hpp"
6
7#include <string.h>
8#include <ctype.h>
9#include <unordered_map>
10#include <algorithm> // std::max
11
12using namespace std;
13
14namespace duckdb {
15
16static string_t repeat_scalar_function(const string_t& str, const int64_t cnt, vector<char> &result) {
17 // Get information about the repeated string
18 const auto input_str = str.GetData();
19 const auto size_str = str.GetSize();
20
21 // Reuse the buffer
22 result.clear();
23 for (auto remaining = cnt; remaining-- > 0;) {
24 result.insert(result.end(), input_str, input_str + size_str);
25 }
26
27 return string_t(result.data(), result.size());
28}
29
30static void repeat_function(DataChunk &args, ExpressionState &state, Vector &result) {
31 assert(args.column_count() == 2 && args.data[0].type == TypeId::VARCHAR && args.data[1].type == TypeId::INT64);
32 auto &str_vector = args.data[0];
33 auto &cnt_vector = args.data[1];
34
35 vector<char> buffer;
36 BinaryExecutor::Execute<string_t, int64_t, string_t>(str_vector, cnt_vector, result, args.size(),
37 [&](string_t str, int64_t cnt) {
38 return StringVector::AddString(result,
39 repeat_scalar_function(str, cnt, buffer));
40 }
41 );
42}
43
44void RepeatFun::RegisterFunction(BuiltinFunctions &set) {
45 set.AddFunction(ScalarFunction("repeat", // name of the function
46 {SQLType::VARCHAR, SQLType::BIGINT}, // argument list
47 SQLType::VARCHAR, // return type
48 repeat_function)); // pointer to function implementation
49}
50
51} // namespace duckdb
52