/
string-functions-ir.cc
1930 lines (1726 loc) · 70.4 KB
/
string-functions-ir.cc
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "exprs/string-functions.h"
#include <cctype>
#include <numeric>
#include <stdint.h>
#include <re2/re2.h>
#include <re2/stringpiece.h>
#include <boost/static_assert.hpp>
#include "exprs/anyval-util.h"
#include "exprs/scalar-expr.h"
#include "gen-cpp/Metrics_types.h"
#include "gutil/strings/charset.h"
#include "gutil/strings/substitute.h"
#include "runtime/string-value.inline.h"
#include "runtime/tuple-row.h"
#include "util/bit-util.h"
#include "util/coding-util.h"
#include "util/pretty-printer.h"
#include "util/string-util.h"
#include "util/ubsan.h"
#include "util/url-parser.h"
#include "common/names.h"
using namespace impala_udf;
using std::bitset;
using std::any_of;
// NOTE: be careful not to use string::append. It is not performant.
namespace impala {
const char* ERROR_CHARACTER_LIMIT_EXCEEDED =
"$0 is larger than allowed limit of $1 character data.";
uint64_t StringFunctions::re2_mem_limit_ = 8 << 20;
// This behaves identically to the mysql implementation, namely:
// - 1-indexed positions
// - supported negative positions (count from the end of the string)
// - [optional] len. No len indicates longest substr possible
StringVal StringFunctions::Substring(FunctionContext* context,
const StringVal& str, const BigIntVal& pos, const BigIntVal& len) {
if (str.is_null || pos.is_null || len.is_null) return StringVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE)) {
return Utf8Substring(context, str, pos, len);
}
int fixed_pos = pos.val;
if (fixed_pos < 0) fixed_pos = str.len + fixed_pos + 1;
int max_len = str.len - fixed_pos + 1;
int fixed_len = ::min(static_cast<int>(len.val), max_len);
if (fixed_pos > 0 && fixed_pos <= str.len && fixed_len > 0) {
return StringVal(str.ptr + fixed_pos - 1, fixed_len);
} else {
return StringVal();
}
}
StringVal StringFunctions::Substring(FunctionContext* context,
const StringVal& str, const BigIntVal& pos) {
// StringVal.len is an int => INT32_MAX
return Substring(context, str, pos, BigIntVal(INT32_MAX));
}
StringVal StringFunctions::Utf8Substring(FunctionContext* context, const StringVal& str,
const BigIntVal& pos) {
return Utf8Substring(context, str, pos, BigIntVal(INT32_MAX));
}
StringVal StringFunctions::Utf8Substring(FunctionContext* context, const StringVal& str,
const BigIntVal& pos, const BigIntVal& len) {
if (str.is_null || pos.is_null || len.is_null) return StringVal::null();
if (str.len == 0 || pos.val == 0 || len.val <= 0) return StringVal();
int byte_pos;
int utf8_cnt = 0;
// pos.val starts at 1 (1-indexed positions).
if (pos.val > 0) {
// Seek to the start byte of the pos-th UTF-8 character.
for (byte_pos = 0; utf8_cnt < pos.val && byte_pos < str.len; ++byte_pos) {
if (BitUtil::IsUtf8StartByte(str.ptr[byte_pos])) ++utf8_cnt;
}
// Not enough UTF-8 characters.
if (utf8_cnt < pos.val) return StringVal();
// Back to the start byte of the pos-th UTF-8 character.
--byte_pos;
int byte_start = byte_pos;
// Seek to the end until we get enough UTF-8 characters.
for (utf8_cnt = 0; utf8_cnt < len.val && byte_pos < str.len; ++byte_pos) {
if (BitUtil::IsUtf8StartByte(str.ptr[byte_pos])) ++utf8_cnt;
}
if (utf8_cnt == len.val) {
// We are now at the middle byte of the last UTF-8 character. Seek to the end of it.
while (byte_pos < str.len && !BitUtil::IsUtf8StartByte(str.ptr[byte_pos])) {
++byte_pos;
}
}
return StringVal(str.ptr + byte_start, byte_pos - byte_start);
}
// pos.val is negative. Seek from the end of the string.
int byte_end = str.len;
utf8_cnt = 0;
byte_pos = str.len - 1;
while (utf8_cnt < -pos.val && byte_pos >= 0) {
if (BitUtil::IsUtf8StartByte(str.ptr[byte_pos])) {
++utf8_cnt;
// Remember the end of the substring's last UTF-8 character.
if (utf8_cnt > 0 && utf8_cnt == -pos.val - len.val) byte_end = byte_pos;
}
--byte_pos;
}
// Not enough UTF-8 characters.
if (utf8_cnt < -pos.val) return StringVal();
// Back to the start byte of the substring's first UTF-8 character.
++byte_pos;
return StringVal(str.ptr + byte_pos, byte_end - byte_pos);
}
// This behaves identically to the mysql implementation.
StringVal StringFunctions::Left(
FunctionContext* context, const StringVal& str, const BigIntVal& len) {
return Substring(context, str, 1, len);
}
// This behaves identically to the mysql implementation.
StringVal StringFunctions::Right(
FunctionContext* context, const StringVal& str, const BigIntVal& len) {
// Don't index past the beginning of str, otherwise we'll get an empty string back
int64_t pos = ::max(-len.val, static_cast<int64_t>(-str.len));
return Substring(context, str, BigIntVal(pos), len);
}
StringVal StringFunctions::Space(FunctionContext* context, const BigIntVal& len) {
if (len.is_null) return StringVal::null();
if (len.val <= 0) return StringVal();
if (len.val > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"space() result",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
StringVal result(context, len.val);
if (UNLIKELY(result.is_null)) return StringVal::null();
memset(result.ptr, ' ', len.val);
return result;
}
StringVal StringFunctions::Repeat(
FunctionContext* context, const StringVal& str, const BigIntVal& n) {
if (str.is_null || n.is_null) return StringVal::null();
if (str.len == 0 || n.val <= 0) return StringVal();
if (n.val > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"Number of repeats in repeat() call",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
static_assert(numeric_limits<int64_t>::max() / numeric_limits<int>::max()
>= StringVal::MAX_LENGTH,
"multiplying StringVal::len with positive int fits in int64_t");
int64_t out_len = str.len * n.val;
if (out_len > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"repeat() result",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
StringVal result(context, static_cast<int>(out_len));
if (UNLIKELY(result.is_null)) return StringVal::null();
uint8_t* ptr = result.ptr;
for (int64_t i = 0; i < n.val; ++i) {
memcpy(ptr, str.ptr, str.len);
ptr += str.len;
}
return result;
}
StringVal StringFunctions::Lpad(FunctionContext* context, const StringVal& str,
const BigIntVal& len, const StringVal& pad) {
if (str.is_null || len.is_null || pad.is_null || len.val < 0) return StringVal::null();
// Corner cases: Shrink the original string, or leave it alone.
// TODO: Hive seems to go into an infinite loop if pad.len == 0,
// so we should pay attention to Hive's future solution to be compatible.
if (len.val <= str.len || pad.len == 0) return StringVal(str.ptr, len.val);
if (len.val > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"lpad() result",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
StringVal result(context, len.val);
if (UNLIKELY(result.is_null)) return StringVal::null();
int padded_prefix_len = len.val - str.len;
int pad_index = 0;
int result_index = 0;
uint8_t* ptr = result.ptr;
// Prepend chars of pad.
while (result_index < padded_prefix_len) {
ptr[result_index++] = pad.ptr[pad_index++];
pad_index = pad_index % pad.len;
}
// Append given string.
memcpy(ptr + result_index, str.ptr, str.len);
return result;
}
StringVal StringFunctions::Rpad(FunctionContext* context, const StringVal& str,
const BigIntVal& len, const StringVal& pad) {
if (str.is_null || len.is_null || pad.is_null || len.val < 0) return StringVal::null();
// Corner cases: Shrink the original string, or leave it alone.
// TODO: Hive seems to go into an infinite loop if pad->len == 0,
// so we should pay attention to Hive's future solution to be compatible.
if (len.val <= str.len || pad.len == 0) {
return StringVal(str.ptr, len.val);
}
if (len.val > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"rpad() result",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
StringVal result(context, len.val);
if (UNLIKELY(result.is_null)) return StringVal::null();
memcpy(result.ptr, str.ptr, str.len);
// Append chars of pad until desired length
uint8_t* ptr = result.ptr;
int pad_index = 0;
int result_len = str.len;
while (result_len < len.val) {
ptr[result_len++] = pad.ptr[pad_index++];
pad_index = pad_index % pad.len;
}
return result;
}
IntVal StringFunctions::Length(FunctionContext* context, const StringVal& str) {
if (str.is_null) return IntVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE, 0)) {
return Utf8Length(context, str);
}
return IntVal(str.len);
}
IntVal StringFunctions::Bytes(FunctionContext* context,const StringVal& str){
if(str.is_null) return IntVal::null();
return IntVal(str.len);
}
IntVal StringFunctions::CharLength(FunctionContext* context, const StringVal& str) {
if (str.is_null) return IntVal::null();
const FunctionContext::TypeDesc* t = context->GetArgType(0);
DCHECK_EQ(t->type, FunctionContext::TYPE_FIXED_BUFFER);
return StringValue::UnpaddedCharLength(reinterpret_cast<char*>(str.ptr), t->len);
}
static int CountUtf8Chars(uint8_t* ptr, int len) {
if (ptr == nullptr) return 0;
int cnt = 0;
for (int i = 0; i < len; ++i) {
if (BitUtil::IsUtf8StartByte(ptr[i])) ++cnt;
}
return cnt;
}
IntVal StringFunctions::Utf8Length(FunctionContext* context, const StringVal& str) {
if (str.is_null) return IntVal::null();
return IntVal(CountUtf8Chars(str.ptr, str.len));
}
StringVal StringFunctions::Lower(FunctionContext* context, const StringVal& str) {
if (str.is_null) return StringVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE)) {
return LowerUtf8(context, str);
}
return LowerAscii(context, str);
}
StringVal StringFunctions::LowerAscii(FunctionContext* context, const StringVal& str) {
// Not in UTF-8 mode, only English alphabetic characters will be converted.
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return StringVal::null();
for (int i = 0; i < str.len; ++i) {
result.ptr[i] = ::tolower(str.ptr[i]);
}
return result;
}
StringVal StringFunctions::Upper(FunctionContext* context, const StringVal& str) {
if (str.is_null) return StringVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE)) {
return UpperUtf8(context, str);
}
return UpperAscii(context, str);
}
StringVal StringFunctions::UpperAscii(FunctionContext* context, const StringVal& str) {
// Not in UTF-8 mode, only English alphabetic characters will be converted.
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return StringVal::null();
for (int i = 0; i < str.len; ++i) {
result.ptr[i] = ::toupper(str.ptr[i]);
}
return result;
}
// Returns a string identical to the input, but with the first character
// of each word mapped to its upper-case equivalent. All other characters
// will be mapped to their lower-case equivalents. If input == NULL it
// will return NULL
StringVal StringFunctions::InitCap(FunctionContext* context, const StringVal& str) {
if (str.is_null) return StringVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE)) {
return InitCapUtf8(context, str);
}
return InitCapAscii(context, str);
}
StringVal StringFunctions::InitCapAscii(FunctionContext* context, const StringVal& str) {
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return StringVal::null();
uint8_t* result_ptr = result.ptr;
bool word_start = true;
for (int i = 0; i < str.len; ++i) {
if (isspace(str.ptr[i])) {
result_ptr[i] = str.ptr[i];
word_start = true;
} else {
result_ptr[i] = (word_start ? toupper(str.ptr[i]) : tolower(str.ptr[i]));
word_start = false;
}
}
return result;
}
/// Reports the error in parsing multibyte characters with leading bytes and current
/// locale. Used in Utf8CaseConversion().
static void ReportErrorBytes(FunctionContext* context, const StringVal& str,
int current_idx) {
DCHECK_LT(current_idx, str.len);
stringstream ss;
ss << "[0x" << std::hex << (int)DCHECK_NOTNULL(str.ptr)[current_idx];
for (int k = 1; k < 4 && current_idx + k < str.len; ++k) {
ss << ", 0x" << std::hex << (int)str.ptr[current_idx + k];
}
ss << "]";
context->AddWarning(Substitute(
"Illegal multi-byte character in string. Leading bytes: $0. Current locale: $1",
ss.str(), std::locale("").name()).c_str());
}
/// Converts string based on the transform function 'fn'. The unit of the conversion is
/// a wchar_t (i.e. uint32_t) which is parsed from multi bytes using std::mbtowc().
/// The transform function 'fn' accepts two parameters: the original wchar_t and a flag
/// indicating whether it's the first character of a word.
/// After the transformation, the wchar_t is converted back to bytes.
static StringVal Utf8CaseConversion(FunctionContext* context, const StringVal& str,
uint32_t (*fn)(uint32_t, bool*)) {
// Usually the upper/lower cases have the same size in bytes. Here we add 4 bytes
// buffer in case of illegal Unicodes.
int max_result_bytes = str.len + 4;
StringVal result(context, max_result_bytes);
if (UNLIKELY(result.is_null)) return StringVal::null();
wchar_t wc;
int wc_bytes;
bool word_start = true;
uint8_t* result_ptr = result.ptr;
std::mbstate_t wc_state{};
std::mbstate_t mb_state{};
for (int i = 0; i < str.len; i += wc_bytes) {
// std::mbtowc converts a multibyte sequence to a wide character. It's not
// thread safe. Here we use std::mbrtowc instead.
wc_bytes = std::mbrtowc(&wc, reinterpret_cast<char*>(str.ptr + i), str.len - i,
&wc_state);
bool needs_conversion = true;
if (wc_bytes == 0) {
// std::mbtowc returns 0 when hitting '\0'.
wc = 0;
wc_bytes = 1;
} else if (wc_bytes < 0) {
ReportErrorBytes(context, str, i);
// Replace it to the replacement character (U+FFFD)
wc = 0xFFFD;
needs_conversion = false;
// Jump to the next legal UTF-8 start byte.
wc_bytes = 1;
while (i + wc_bytes < str.len && !BitUtil::IsUtf8StartByte(str.ptr[i + wc_bytes])) {
wc_bytes++;
}
}
if (needs_conversion) wc = fn(wc, &word_start);
// std::wctomb converts a wide character to a multibyte sequence. It's not
// thread safe. Here we use std::wcrtomb instead.
int res_bytes = std::wcrtomb(reinterpret_cast<char*>(result_ptr), wc, &mb_state);
if (res_bytes <= 0) {
if (needs_conversion) {
context->AddWarning(Substitute(
"Ignored illegal wide character in results: $0. Current locale: $1",
wc, std::locale("").name()).c_str());
}
continue;
}
result_ptr += res_bytes;
if (result_ptr - result.ptr > max_result_bytes - 4) {
// Double the result buffer for overflow
max_result_bytes *= 2;
max_result_bytes = min<int>(StringVal::MAX_LENGTH,
static_cast<int>(BitUtil::RoundUpToPowerOfTwo(max_result_bytes)));
int offset = result_ptr - result.ptr;
if (UNLIKELY(!result.Resize(context, max_result_bytes))) return StringVal::null();
result_ptr = result.ptr + offset;
}
}
result.len = result_ptr - result.ptr;
return result;
}
StringVal StringFunctions::LowerUtf8(FunctionContext* context, const StringVal& str) {
return Utf8CaseConversion(context, str,
[](uint32_t wide_char, bool* word_start) {
return std::towlower(wide_char);
});
}
StringVal StringFunctions::UpperUtf8(FunctionContext* context, const StringVal& str) {
return Utf8CaseConversion(context, str,
[](uint32_t wide_char, bool* word_start) {
return std::towupper(wide_char);
});
}
StringVal StringFunctions::InitCapUtf8(FunctionContext* context, const StringVal& str) {
return Utf8CaseConversion(context, str,
[](uint32_t wide_char, bool* word_start) {
if (UNLIKELY(iswspace(wide_char))) {
*word_start = true;
return wide_char;
}
uint32_t res = *word_start ? std::towupper(wide_char) : std::towlower(wide_char);
*word_start = false;
return res;
});
}
struct ReplaceContext {
ReplaceContext(StringVal *pattern_in) {
pattern = StringValue::FromStringVal(*pattern_in);
search = StringSearch(&pattern);
}
StringValue pattern;
StringSearch search;
};
void StringFunctions::ReplacePrepare(FunctionContext* context,
FunctionContext::FunctionStateScope scope) {
if (scope != FunctionContext::FRAGMENT_LOCAL) return;
if (!context->IsArgConstant(1)) return;
DCHECK_EQ(context->GetArgType(1)->type, FunctionContext::TYPE_STRING);
StringVal* pattern = reinterpret_cast<StringVal*>(context->GetConstantArg(1));
if (pattern->is_null || pattern->len == 0) return;
struct ReplaceContext* replace = context->Allocate<ReplaceContext>();
if (replace != nullptr) {
new(replace) ReplaceContext(pattern);
context->SetFunctionState(scope, replace);
}
}
void StringFunctions::ReplaceClose(FunctionContext* context,
FunctionContext::FunctionStateScope scope) {
if (scope != FunctionContext::FRAGMENT_LOCAL) return;
ReplaceContext* rptr = reinterpret_cast<ReplaceContext*>
(context->GetFunctionState(FunctionContext::FRAGMENT_LOCAL));
context->Free(reinterpret_cast<uint8_t*>(rptr));
context->SetFunctionState(scope, nullptr);
}
StringVal StringFunctions::Replace(FunctionContext* context, const StringVal& str,
const StringVal& pattern, const StringVal& replace) {
DCHECK_LE(str.len, StringVal::MAX_LENGTH);
DCHECK_LE(pattern.len, StringVal::MAX_LENGTH);
DCHECK_LE(replace.len, StringVal::MAX_LENGTH);
if (str.is_null || pattern.is_null || replace.is_null) return StringVal::null();
if (pattern.len == 0 || pattern.len > str.len) return str;
// StringSearch keeps a pointer to the StringValue object, so it must remain
// in scope if used.
StringSearch search;
StringValue needle;
const StringSearch *search_ptr;
const ReplaceContext* rptr = reinterpret_cast<ReplaceContext*>
(context->GetFunctionState(FunctionContext::FRAGMENT_LOCAL));
if (UNLIKELY(rptr == nullptr)) {
needle = StringValue::FromStringVal(pattern);
search = StringSearch(&needle);
search_ptr = &search;
} else {
search_ptr = &rptr->search;
}
const StringValue haystack = StringValue::FromStringVal(str);
int64_t match_pos = search_ptr->Search(&haystack);
// No match? Skip everything.
if (match_pos < 0) return str;
StringValue::SimpleString haystack_s = haystack.ToSimpleString();
DCHECK_GT(pattern.len, 0);
DCHECK_GE(haystack_s.len, pattern.len);
int buffer_space;
const int delta = replace.len - pattern.len;
// MAX_LENGTH is unsigned, so convert back to int to do correctly signed compare
DCHECK_LE(delta, static_cast<int>(StringVal::MAX_LENGTH) - 1);
if ((delta > 0 && delta < 128) && haystack_s.len <= 128) {
// Quick estimate for potential matches - this heuristic is needed to win
// over regexp_replace on expanding patterns. 128 is arbitrarily chosen so
// we can't massively over-estimate the buffer size.
int matches_possible = 0;
char c = pattern.ptr[0];
for (int i = 0; i <= haystack_s.len - pattern.len; ++i) {
if (haystack_s.ptr[i] == c) ++matches_possible;
}
buffer_space = haystack_s.len + matches_possible * delta;
} else {
// Note - cannot overflow because pattern.len is at least one
static_assert(StringVal::MAX_LENGTH - 1 + StringVal::MAX_LENGTH <=
std::numeric_limits<decltype(buffer_space)>::max(),
"Buffer space computation can overflow");
buffer_space = haystack_s.len + delta;
}
StringVal result(context, buffer_space);
// result may be NULL if we went over MAX_LENGTH or the allocation failed.
if (UNLIKELY(result.is_null)) return result;
uint8_t* ptr = result.ptr;
int consumed = 0;
while (match_pos + pattern.len <= haystack_s.len) {
// Copy in original string
const int unmatched_bytes = match_pos - consumed;
memcpy(ptr, &haystack_s.ptr[consumed], unmatched_bytes);
DCHECK_LE(ptr - result.ptr + unmatched_bytes, buffer_space);
ptr += unmatched_bytes;
// Copy in replacement - always safe since we always leave room for one more replace
DCHECK_LE(ptr - result.ptr + replace.len, buffer_space);
Ubsan::MemCpy(ptr, replace.ptr, replace.len);
ptr += replace.len;
// Don't want to re-match within already replaced pattern
match_pos += pattern.len;
consumed = match_pos;
StringValue haystack_substring = haystack.Substring(match_pos);
int match_pos_in_substring = search_ptr->Search(&haystack_substring);
if (match_pos_in_substring < 0) break;
match_pos += match_pos_in_substring;
// If we had an enlarging pattern, we may need more space
if (delta > 0) {
const int bytes_produced = ptr - result.ptr;
const int bytes_remaining = haystack_s.len - consumed;
DCHECK_LE(bytes_produced, StringVal::MAX_LENGTH);
DCHECK_LE(bytes_remaining, StringVal::MAX_LENGTH - 1);
// Note: by above, cannot overflow
const int min_output = bytes_produced + bytes_remaining;
DCHECK_LE(min_output, StringVal::MAX_LENGTH);
// Also no overflow: min_output <= MAX_LENGTH and delta <= MAX_LENGTH - 1
const int64_t space_needed = min_output + delta;
if (UNLIKELY(space_needed > buffer_space)) {
// Check to see if we can allocate a large enough buffer.
if (space_needed > StringVal::MAX_LENGTH) {
context->SetError(Substitute(ERROR_CHARACTER_LIMIT_EXCEEDED,
"replace() result",
PrettyPrinter::Print(StringVal::MAX_LENGTH, TUnit::BYTES)).c_str());
return StringVal::null();
}
// Double the buffer size whenever it fills up to amortise cost of resizing.
// Must compute next power of two using 64-bit math to avoid signed overflow.
buffer_space = min<int>(StringVal::MAX_LENGTH,
static_cast<int>(BitUtil::RoundUpToPowerOfTwo(space_needed)));
// Give up if the allocation fails or we hit an error. This prevents us from
// continuing to blow past the mem limit.
if (UNLIKELY(!result.Resize(context, buffer_space) || context->has_error())) {
return StringVal::null();
}
// Don't forget to move the pointer
ptr = result.ptr + bytes_produced;
}
}
}
// Copy in remainder and re-adjust size
const int bytes_remaining = haystack_s.len - consumed;
result.len = ptr - result.ptr + bytes_remaining;
DCHECK_LE(result.len, buffer_space);
memcpy(ptr, &haystack_s.ptr[consumed], bytes_remaining);
return result;
}
StringVal StringFunctions::Reverse(FunctionContext* context, const StringVal& str) {
if (str.is_null) return StringVal::null();
if (context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE)) {
return Utf8Reverse(context, str);
}
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return StringVal::null();
BitUtil::ByteSwap(result.ptr, str.ptr, str.len);
return result;
}
static inline void InPlaceReverse(uint8_t* ptr, int len) {
for (int i = 0, j = len - 1; i < j; ++i, --j) {
uint8_t tmp = ptr[i];
ptr[i] = ptr[j];
ptr[j] = tmp;
}
}
// Returns a string with the UTF-8 characters (code points) in revrese order. Note that
// this function operates on Unicode code points and not user visible characters (or
// grapheme clusters). This is consistent with other systems, e.g. Hive, SparkSQL.
StringVal StringFunctions::Utf8Reverse(FunctionContext* context, const StringVal& str) {
if (str.is_null) return StringVal::null();
if (str.len == 0) return StringVal();
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return StringVal::null();
// First make a copy of the reversed string.
BitUtil::ByteSwap(result.ptr, str.ptr, str.len);
// Then reverse bytes inside each UTF-8 character.
int last = result.len;
for (int i = result.len - 1; i >= 0; --i) {
if (BitUtil::IsUtf8StartByte(result.ptr[i])) {
// Only reverse bytes of a UTF-8 character
if (last - i > 1) InPlaceReverse(result.ptr + i + 1, last - i);
last = i;
}
}
if (last > 0) InPlaceReverse(result.ptr, last + 1);
return result;
}
StringVal StringFunctions::Translate(FunctionContext* context, const StringVal& str,
const StringVal& src, const StringVal& dst) {
if (str.is_null || src.is_null || dst.is_null) return StringVal::null();
StringVal result(context, str.len);
if (UNLIKELY(result.is_null)) return result;
// TODO: if we know src and dst are constant, we can prebuild a conversion
// table to remove the inner loop.
int result_len = 0;
for (int i = 0; i < str.len; ++i) {
bool matched_src = false;
for (int j = 0; j < src.len; ++j) {
if (str.ptr[i] == src.ptr[j]) {
if (j < dst.len) {
result.ptr[result_len++] = dst.ptr[j];
} else {
// src[j] doesn't map to any char in dst, the char is dropped.
}
matched_src = true;
break;
}
}
if (!matched_src) result.ptr[result_len++] = str.ptr[i];
}
result.len = result_len;
return result;
}
void StringFunctions::TrimContext::Reset(const StringVal& chars_to_trim) {
single_byte_chars_.reset();
double_byte_chars_.clear();
triple_byte_chars_.clear();
quadruple_byte_chars_.clear();
if (!utf8_mode_) {
for (size_t i = 0; i < chars_to_trim.len; ++i) {
single_byte_chars_.set(chars_to_trim.ptr[i], true);
}
return;
}
for (size_t i = 0, char_size = 0; i < chars_to_trim.len; i += char_size) {
char_size = BitUtil::NumBytesInUtf8Encoding(chars_to_trim.ptr[i]);
// If the remaining number of bytes does not match the number of bytes specified by
// the UTF-8 character, we may have encountered an illegal UTF-8 character.
// In order to prevent subsequent data access from going out of bounds, restrictions
// are placed here to ensure that accessing pointers to multi-byte characters is
// always safe.
if (UNLIKELY(i + char_size > chars_to_trim.len)) {
char_size = chars_to_trim.len - i;
}
switch (char_size) {
case 1: single_byte_chars_.set(chars_to_trim.ptr[i], true); break;
case 2: double_byte_chars_.push_back(&chars_to_trim.ptr[i]); break;
case 3: triple_byte_chars_.push_back(&chars_to_trim.ptr[i]); break;
case 4: quadruple_byte_chars_.push_back(&chars_to_trim.ptr[i]); break;
default: DCHECK(false); break;
}
}
}
bool StringFunctions::TrimContext::Contains(const uint8_t* utf8_char, int len) const {
auto eq = [&](const uint8_t* c){ return memcmp(c, utf8_char, len) == 0; };
switch (len) {
case 1: return single_byte_chars_.test(*utf8_char);
case 2: return any_of(double_byte_chars_.begin(), double_byte_chars_.end(), eq);
case 3: return any_of(triple_byte_chars_.begin(), triple_byte_chars_.end(), eq);
case 4: return any_of(quadruple_byte_chars_.begin(), quadruple_byte_chars_.end(), eq);
default: DCHECK(false); return false;
}
}
void StringFunctions::TrimPrepare(FunctionContext* context,
FunctionContext::FunctionStateScope scope) {
bool utf8_mode = context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE);
DoTrimPrepare(context, scope, utf8_mode);
}
void StringFunctions::Utf8TrimPrepare(FunctionContext* context,
FunctionContext::FunctionStateScope scope) {
DoTrimPrepare(context, scope, true /* utf8_mode */);
}
void StringFunctions::DoTrimPrepare(FunctionContext* context,
FunctionContext::FunctionStateScope scope, bool utf8_mode) {
if (scope != FunctionContext::THREAD_LOCAL) return;
TrimContext* trim_ctx = new TrimContext(utf8_mode);
context->SetFunctionState(scope, trim_ctx);
// If the caller didn't specify the set of characters to trim, it means
// that we're only trimming whitespace. Return early in that case.
// There can be either 1 or 2 arguments.
DCHECK(context->GetNumArgs() == 1 || context->GetNumArgs() == 2);
if (context->GetNumArgs() == 1) {
trim_ctx->Reset(StringVal(" "));
return;
}
if (!context->IsArgConstant(1)) return;
DCHECK_EQ(context->GetArgType(1)->type, FunctionContext::TYPE_STRING);
StringVal* chars_to_trim = reinterpret_cast<StringVal*>(context->GetConstantArg(1));
if (chars_to_trim->is_null) return; // We shouldn't peek into Null StringVals
trim_ctx->Reset(*chars_to_trim);
}
void StringFunctions::TrimClose(
FunctionContext* context, FunctionContext::FunctionStateScope scope) {
if (scope != FunctionContext::THREAD_LOCAL) return;
TrimContext* trim_ctx =
reinterpret_cast<TrimContext*>(context->GetFunctionState(scope));
delete trim_ctx;
context->SetFunctionState(scope, nullptr);
}
template <StringFunctions::TrimPosition D, bool IS_IMPLICIT_WHITESPACE>
StringVal StringFunctions::DoTrimString(FunctionContext* ctx,
const StringVal& str, const StringVal& chars_to_trim) {
if (str.is_null) return StringVal::null();
TrimContext* trim_ctx = reinterpret_cast<TrimContext*>(
ctx->GetFunctionState(FunctionContext::THREAD_LOCAL));
// When 'chars_to_trim' is not a constant, we need to reset TrimContext with new
// 'chars_to_trim'.
if (!IS_IMPLICIT_WHITESPACE && !ctx->IsArgConstant(1)) {
if (chars_to_trim.is_null) return str;
trim_ctx->Reset(chars_to_trim);
}
// When dealing with UTF-8 characters in UTF-8 mode, use DoUtf8TrimString().
if (trim_ctx->utf8_mode()) {
return DoUtf8TrimString<D>(str, *trim_ctx);
}
// Otherwise, we continue to maintain the old behavior.
int32_t begin = 0;
int32_t end = str.len - 1;
// Find new starting position.
if constexpr (D == LEADING || D == BOTH) {
while (begin < str.len && trim_ctx->Contains(str.ptr[begin])) {
++begin;
}
}
// Find new ending position.
if constexpr (D == TRAILING || D == BOTH) {
while (end >= begin && trim_ctx->Contains(str.ptr[end])) {
--end;
}
}
return StringVal(str.ptr + begin, end - begin + 1);
}
template <StringFunctions::TrimPosition D>
StringVal StringFunctions::DoUtf8TrimString(const StringVal& str,
const TrimContext& trim_ctx) {
if (UNLIKELY(str.len == 0)) return str;
const uint8_t* begin = str.ptr;
const uint8_t* end = begin + str.len;
// Find new starting position.
if constexpr (D == LEADING || D == BOTH) {
while (begin < end) {
size_t char_size = BitUtil::NumBytesInUtf8Encoding(*begin);
if (UNLIKELY(begin + char_size > end)) char_size = end - begin;
if (!trim_ctx.Contains(begin, char_size)) break;
begin += char_size;
}
}
// Find new ending position.
if constexpr (D == TRAILING || D == BOTH) {
while (begin < end) {
int char_index = FindUtf8PosBackward(begin, end - begin, 0);
DCHECK_NE(char_index, -1);
const uint8_t* char_begin = begin + char_index;
if (!trim_ctx.Contains(char_begin, end - char_begin)) break;
end = char_begin;
}
}
return StringVal(const_cast<uint8_t*>(begin), end - begin);
}
StringVal StringFunctions::Trim(FunctionContext* context, const StringVal& str) {
return DoTrimString<BOTH, true>(context, str, StringVal(" "));
}
StringVal StringFunctions::Ltrim(FunctionContext* context, const StringVal& str) {
return DoTrimString<LEADING, true>(context, str, StringVal(" "));
}
StringVal StringFunctions::Rtrim(FunctionContext* context, const StringVal& str) {
return DoTrimString<TRAILING, true>(context, str, StringVal(" "));
}
StringVal StringFunctions::LTrimString(FunctionContext* ctx,
const StringVal& str, const StringVal& chars_to_trim) {
return DoTrimString<LEADING, false>(ctx, str, chars_to_trim);
}
StringVal StringFunctions::RTrimString(FunctionContext* ctx,
const StringVal& str, const StringVal& chars_to_trim) {
return DoTrimString<TRAILING, false>(ctx, str, chars_to_trim);
}
StringVal StringFunctions::BTrimString(FunctionContext* ctx,
const StringVal& str, const StringVal& chars_to_trim) {
return DoTrimString<BOTH, false>(ctx, str, chars_to_trim);
}
IntVal StringFunctions::Ascii(FunctionContext* context, const StringVal& str) {
if (str.is_null) return IntVal::null();
// Hive returns 0 when given an empty string.
return IntVal((str.len == 0) ? 0 : static_cast<int32_t>(str.ptr[0]));
}
IntVal StringFunctions::Instr(FunctionContext* context, const StringVal& str,
const StringVal& substr, const BigIntVal& start_position,
const BigIntVal& occurrence) {
if (str.is_null || substr.is_null || start_position.is_null || occurrence.is_null) {
return IntVal::null();
}
if (occurrence.val <= 0) {
stringstream ss;
ss << "Invalid occurrence parameter to instr function: " << occurrence.val;
context->SetError(ss.str().c_str());
return IntVal(0);
}
if (start_position.val == 0) return IntVal(0);
bool utf8_mode = context->impl()->GetConstFnAttr(FunctionContextImpl::UTF8_MODE);
StringValue haystack = StringValue::FromStringVal(str);
StringValue::SimpleString haystack_s = haystack.ToSimpleString();
StringValue needle = StringValue::FromStringVal(substr);
StringValue::SimpleString needle_s = needle.ToSimpleString();
StringSearch search(&needle);
int match_pos = -1;
if (start_position.val > 0) {
// A positive starting position indicates regular searching from the left.
int search_start_pos = start_position.val - 1;
if (utf8_mode) {
search_start_pos = FindUtf8PosForward(str.ptr, str.len, search_start_pos);
}
if (search_start_pos >= haystack_s.len) return IntVal(0);
for (int match_num = 0; match_num < occurrence.val; ++match_num) {
DCHECK_LE(search_start_pos, haystack_s.len);
StringValue haystack_substring = haystack.Substring(search_start_pos);
int match_pos_in_substring = search.Search(&haystack_substring);
if (match_pos_in_substring < 0) return IntVal(0);
match_pos = search_start_pos + match_pos_in_substring;
search_start_pos = match_pos + 1;
}
} else {
// A negative starting position indicates searching from the right.
int search_start_pos = utf8_mode ?
FindUtf8PosBackward(str.ptr, str.len, -start_position.val - 1) :
haystack_s.len + start_position.val;
// The needle must fit between search_start_pos and the end of the string
if (search_start_pos + needle_s.len > haystack_s.len) {
search_start_pos = haystack_s.len - needle_s.len;
}
if (search_start_pos < 0) return IntVal(0);
for (int match_num = 0; match_num < occurrence.val; ++match_num) {
DCHECK_GE(search_start_pos + needle_s.len, 0);
DCHECK_LE(search_start_pos + needle_s.len, haystack_s.len);
StringValue haystack_substring =
haystack.Substring(0, search_start_pos + needle_s.len);
match_pos = search.RSearch(&haystack_substring);
if (match_pos < 0) return IntVal(0);
search_start_pos = match_pos - 1;
}
}
// In UTF8 mode, positions are counted by Unicode characters in UTF8 encoding.
// If not in UTF8 mode, return positions starting from 1 at the leftmost position.
return utf8_mode ? IntVal(CountUtf8Chars(str.ptr, match_pos) + 1) :
IntVal(match_pos + 1);
}
IntVal StringFunctions::Instr(FunctionContext* context, const StringVal& str,
const StringVal& substr, const BigIntVal& start_position) {
return Instr(context, str, substr, start_position, BigIntVal(1));
}
IntVal StringFunctions::Instr(
FunctionContext* context, const StringVal& str, const StringVal& substr) {
return Instr(context, str, substr, BigIntVal(1), BigIntVal(1));
}
IntVal StringFunctions::Locate(FunctionContext* context, const StringVal& substr,
const StringVal& str) {
return Instr(context, str, substr);
}
IntVal StringFunctions::LocatePos(FunctionContext* context, const StringVal& substr,
const StringVal& str, const BigIntVal& start_pos) {
if (str.is_null || substr.is_null || start_pos.is_null) return IntVal::null();
// Hive returns 0 for *start_pos <= 0,
// but throws an exception for *start_pos > str->len.
// Since returning 0 seems to be Hive's error condition, return 0.
if (start_pos.val <= 0 || start_pos.val > str.len) return IntVal(0);
return Instr(context, str, substr, start_pos);
}
// The caller owns the returned regex. Returns NULL if the pattern could not be compiled.
re2::RE2* CompileRegex(const StringVal& pattern, string* error_str,
const StringVal& match_parameter) {
DCHECK(error_str != NULL);
re2::StringPiece pattern_sp(reinterpret_cast<char*>(pattern.ptr), pattern.len);
re2::RE2::Options options;
// Disable error logging in case e.g. every row causes an error
options.set_log_errors(false);
// Return the leftmost longest match (rather than the first match).
options.set_longest_match(true);
// Set the maximum memory used by re2's regex engine for storage
StringFunctions::SetRE2MemOpt(&options);
if (!match_parameter.is_null &&
!StringFunctions::SetRE2Options(match_parameter, error_str, &options)) {
return NULL;
}
re2::RE2* re = new re2::RE2(pattern_sp, options);
if (!re->ok()) {
stringstream ss;
ss << "Could not compile regexp pattern: " << AnyValUtil::ToString(pattern) << endl
<< "Error: " << re->error();
*error_str = ss.str();
delete re;
return NULL;
}
return re;
}
// This function sets options in the RE2 library before pattern matching.
bool StringFunctions::SetRE2Options(const StringVal& match_parameter,
string* error_str, re2::RE2::Options* opts) {
for (int i = 0; i < match_parameter.len; i++) {