add before and before last.

This commit is contained in:
publicmatt 2023-12-19 20:31:32 -08:00
parent 1ab09a261e
commit ae491d2bae
2 changed files with 56 additions and 6 deletions

View File

@ -28,8 +28,8 @@ psql
- [x] after
- [] afterLast
- [x] ascii
- [] before
- [] beforeLast
- [x] before
- [x] beforeLast
- [] between
- [x] camel
- [x] contains

View File

@ -1,4 +1,54 @@
// fn str_before<'a>(input: &'a str, search: &str) -> &'a str {
// }
// fn str_beforeLast<'a>(input: &'a str, search: &str) -> &'a str {
// }
use pgrx::prelude::*;
#[pg_extern]
pub fn str_before<'a>(input: &'a str, search: &str) -> &'a str {
local::str_before(input, search)
}
#[pg_extern]
pub fn str_before_last<'a>(input: &'a str, search: &str) -> &'a str {
local::str_before_last(input, search)
}
mod local {
pub fn str_before<'a>(input: &'a str, search: &str) -> &'a str {
if search.is_empty() {
return input;
}
match input.find(search) {
Some(index) => &input[..index],
None => input,
}
}
pub fn str_before_last<'a>(input: &'a str, search: &str) -> &'a str {
match input.rfind(search) {
Some(index) => &input[..index],
None => input,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_str_before() {
assert_eq!(local::str_before("Hello, world!", "world"), "Hello, ");
assert_eq!(local::str_before("Hello, world!", "xyz"), "Hello, world!");
assert_eq!(local::str_before("", "world"), "");
assert_eq!(local::str_before("Hello, world!", ""), "Hello, world!");
}
#[test]
fn test_str_before_last() {
assert_eq!(local::str_before_last("Hello, world!", "o"), "Hello, w");
assert_eq!(
local::str_before_last("Hello, world!", "xyz"),
"Hello, world!"
);
assert_eq!(local::str_before_last("", "world"), "");
assert_eq!(local::str_before_last("Hello, world!", ""), "Hello, world!");
}
}