## Coverage Report

#### Created: 2025-11-22 06:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)

    /Users/andrewlamb/Software/datafusion/datafusion/functions/src/unicode/reverse.rs

    Line
    Count
    Source
    1
    // Licensed to the Apache Software Foundation (ASF) under one
    2
    // or more contributor license agreements.  See the NOTICE file
    3
    // distributed with this work for additional information
    4
    // regarding copyright ownership.  The ASF licenses this file
    5
    // to you under the Apache License, Version 2.0 (the
    6
    // "License"); you may not use this file except in compliance
    7
    // with the License.  You may obtain a copy of the License at
    8
    //
    9
    //   http://www.apache.org/licenses/LICENSE-2.0
    10
    //
    11
    // Unless required by applicable law or agreed to in writing,
    12
    // software distributed under the License is distributed on an
    13
    // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14
    // KIND, either express or implied.  See the License for the
    15
    // specific language governing permissions and limitations
    16
    // under the License.
    17
    18
    use std::any::Any;
    19
    use std::sync::Arc;
    20
    21
    use crate::utils::{make_scalar_function, utf8_to_str_type};
    22
    use arrow::array::{
    23
        Array, ArrayRef, AsArray, GenericStringBuilder, OffsetSizeTrait, StringArrayType,
    24
    };
    25
    use arrow::datatypes::DataType;
    26
    use datafusion_common::{exec_err, Result};
    27
    use datafusion_expr::{
    28
        ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
    29
    };
    30
    use datafusion_macros::user_doc;
    31
    use DataType::{LargeUtf8, Utf8, Utf8View};
    32
    33
    #[user_doc(
    34
        doc_section(label = "String Functions"),
    35
        description = "Reverses the character order of a string.",
    36
        syntax_example = "reverse(str)",
    37
        sql_example = r#"```sql
    38
    > select reverse('datafusion');
    39
    +-----------------------------+
    40
    | reverse(Utf8("datafusion")) |
    41
    +-----------------------------+
    42
    | noisufatad                  |
    43
    +-----------------------------+
    44
    ```"#,
    45
        standard_argument(name = "str", prefix = "String")
    46
    )]
    47
    #[derive(Debug, PartialEq, Eq, Hash)]
    48
    pub struct ReverseFunc {
    49
        signature: Signature,
    50
    }
    51
    52
    impl Default for ReverseFunc {
    53
    0
        fn default() -> Self {
    54
    0
            Self::new()
    55
    0
        }
    56
    }
    57
    58
    impl ReverseFunc {
    59
    0
        pub fn new() -> Self {
    60
            use DataType::*;
    61
    0
            Self {
    62
    0
                signature: Signature::uniform(
    63
    0
                    1,
    64
    0
                    vec![Utf8View, Utf8, LargeUtf8],
    65
    0
                    Volatility::Immutable,
    66
    0
                ),
    67
    0
            }
    68
    0
        }
    69
    }
    70
    71
    impl ScalarUDFImpl for ReverseFunc {
    72
    0
        fn as_any(&self) -> &dyn Any {
    73
    0
            self
    74
    0
        }
    75
    76
    0
        fn name(&self) -> &str {
    77
    0
            "reverse"
    78
    0
        }
    79
    80
    0
        fn signature(&self) -> &Signature {
    81
    0
            &self.signature
    82
    0
        }
    83
    84
    0
        fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
    85
    0
            utf8_to_str_type(&arg_types[0], "reverse")
    86
    0
        }
    87
    88
    0
        fn invoke_with_args(
    89
    0
            &self,
    90
    0
            args: datafusion_expr::ScalarFunctionArgs,
    91
    0
        ) -> Result<ColumnarValue> {
    92
    0
            let args = &args.args;
    93
    0
            match args[0].data_type() {
    94
    0
                Utf8 | Utf8View => make_scalar_function(reverse::<i32>, vec![])(args),
    95
    0
                LargeUtf8 => make_scalar_function(reverse::<i64>, vec![])(args),
    96
    0
                other => {
    97
    0
                    exec_err!("Unsupported data type {other:?} for function reverse")
    98
                }
    99
            }
    100
    0
        }
    101
    102
    0
        fn documentation(&self) -> Option<&Documentation> {
    103
    0
            self.doc()
    104
    0
        }
    105
    }
    106
    107
    /// Reverses the order of the characters in the string `reverse('abcde') = 'edcba'`.
    108
    /// The implementation uses UTF-8 code points as characters
    109
    0
    pub fn reverse<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef> {
    110
    0
        if args[0].data_type() == &Utf8View {
    111
    0
            reverse_impl::<T, _>(args[0].as_string_view())
    112
        } else {
    113
    0
            reverse_impl::<T, _>(args[0].as_string::<T>())
    114
        }
    115
    0
    }
    116
    117
    0
    fn reverse_impl<'a, T: OffsetSizeTrait, V: StringArrayType<'a>>(
    118
    0
        string_array: V,
    119
    0
    ) -> Result<ArrayRef> {
    120
    0
        let mut builder = GenericStringBuilder::<T>::with_capacity(string_array.len(), 1024);
    121
    122
    0
        let mut string_buf = String::new();
    123
    0
        let mut byte_buf = Vec::<u8>::new();
    124
    0
        for string in string_array.iter() {
    125
    0
            if let Some(s) = string {
    126
    0
                if s.is_ascii() {
    127
    0
                    // reverse bytes directly since ASCII characters are single bytes
    128
    0
                    byte_buf.extend(s.as_bytes());
    129
    0
                    byte_buf.reverse();
    130
    0
                    // SAFETY: Since the original string was ASCII, reversing the bytes still results in valid UTF-8.
    131
    0
                    let reversed = unsafe { std::str::from_utf8_unchecked(&byte_buf) };
    132
    0
                    builder.append_value(reversed);
    133
    0
                    byte_buf.clear();
    134
    0
                } else {
    135
    0
                    string_buf.extend(s.chars().rev());
    136
    0
                    builder.append_value(&string_buf);
    137
    0
                    string_buf.clear();
    138
    0
                }
    139
    0
            } else {
    140
    0
                builder.append_null();
    141
    0
            }
    142
        }
    143
    144
    0
        Ok(Arc::new(builder.finish()) as ArrayRef)
    145
    0
    }
    146
    147
    #[cfg(test)]
    148
    mod tests {
    149
        use arrow::array::{Array, LargeStringArray, StringArray};
    150
        use arrow::datatypes::DataType::{LargeUtf8, Utf8};
    151
    152
        use datafusion_common::{Result, ScalarValue};
    153
        use datafusion_expr::{ColumnarValue, ScalarUDFImpl};
    154
    155
        use crate::unicode::reverse::ReverseFunc;
    156
        use crate::utils::test::test_function;
    157
    158
        macro_rules! test_reverse {
    159
            ($INPUT:expr, $EXPECTED:expr) => {
    160
                test_function!(
    161
                    ReverseFunc::new(),
    162
                    vec![ColumnarValue::Scalar(ScalarValue::Utf8($INPUT))],
    163
                    $EXPECTED,
    164
                    &str,
    165
                    Utf8,
    166
                    StringArray
    167
                );
    168
    169
                test_function!(
    170
                    ReverseFunc::new(),
    171
                    vec![ColumnarValue::Scalar(ScalarValue::LargeUtf8($INPUT))],
    172
                    $EXPECTED,
    173
                    &str,
    174
                    LargeUtf8,
    175
                    LargeStringArray
    176
                );
    177
    178
                test_function!(
    179
                    ReverseFunc::new(),
    180
                    vec![ColumnarValue::Scalar(ScalarValue::Utf8View($INPUT))],
    181
                    $EXPECTED,
    182
                    &str,
    183
                    Utf8,
    184
                    StringArray
    185
                );
    186
            };
    187
        }
    188
    189
        #[test]
    190
        fn test_functions() -> Result<()> {
    191
            test_reverse!(Some("abcde".into()), Ok(Some("edcba")));
    192
            test_reverse!(Some("loẅks".into()), Ok(Some("sk̈wol")));
    193
            test_reverse!(Some("loẅks".into()), Ok(Some("sk̈wol")));
    194
            test_reverse!(None, Ok(None));
    195
            #[cfg(not(feature = "unicode_expressions"))]
    196
            test_reverse!(
    197
                Some("abcde".into()),
    198
                internal_err!(
    199
                    "function reverse requires compilation with feature flag: unicode_expressions."
    200
                ),
    201
            );
    202
    203
            Ok(())
    204
        }
    205
    }