Quellcode durchsuchen

Add ord(…) function

David Peter vor 1 Jahr
Ursprung
Commit
c24e7760cd

+ 3 - 0
book/src/conversion-functions.md

@@ -30,6 +30,9 @@ now() -> tz("Asia/Kathmandu")
 # Convert a code point number to a character
 0x2764 -> chr
 
+# Convert a character to a code point number
+"❤" -> ord
+
 # Convert a string to upper/lower case
 "numbat is awesome" -> uppercase
 "vier bis elf weiße Querbänder" -> lowercase

+ 7 - 0
book/src/list-functions-strings.md

@@ -23,6 +23,13 @@ Get a single-character string from a Unicode code point. Example: `0x2764 -> chr
 fn chr(n: Scalar) -> String
 ```
 
+### `ord`
+Get the Unicode code point of the first character in a string. Example: `"❤" -> ord`.
+
+```nbt
+fn ord(s: String) -> Scalar
+```
+
 ### `lowercase`
 Convert a string to lowercase.
 

+ 8 - 0
examples/tests/strings.nbt

@@ -6,6 +6,14 @@ assert_eq(str_slice("hello world", 6, 11), "world")
 assert_eq(str_slice("hello world", 0, 0), "")
 assert_eq(str_slice("hello world", 0, 100), "")
 
+assert_eq(chr(65), "A")
+assert_eq(chr(97), "a")
+assert_eq(chr(0x2764), "❤")
+
+assert_eq(ord("A"), 65)
+assert_eq(ord("a"), 97)
+assert_eq(ord("❤"), 0x2764)
+
 assert_eq(str_append("foo", "bar"), "foobar")
 
 assert(str_contains("hello world", "hello"))

+ 3 - 0
numbat/modules/core/strings.nbt

@@ -11,6 +11,9 @@ fn str_slice(s: String, start: Scalar, end: Scalar) -> String
 @description("Get a single-character string from a Unicode code point. Example: `0x2764 -> chr`")
 fn chr(n: Scalar) -> String
 
+@description("Get the Unicode code point of the first character in a string. Example: `\"❤\" -> ord`")
+fn ord(s: String) -> Scalar
+
 @description("Convert a string to lowercase")
 fn lowercase(s: String) -> String
 

+ 1 - 0
numbat/src/ffi/functions.rs

@@ -83,6 +83,7 @@ pub(crate) fn functions() -> &'static HashMap<String, ForeignFunction> {
         insert_function!(uppercase, 1..=1);
         insert_function!(str_slice, 3..=3);
         insert_function!(chr, 1..=1);
+        insert_function!(ord, 1..=1);
 
         // Date and time
         insert_function!(now, 0..=0);

+ 13 - 0
numbat/src/ffi/strings.rs

@@ -3,6 +3,7 @@ use super::Args;
 use super::Result;
 use crate::quantity::Quantity;
 use crate::value::Value;
+use crate::RuntimeError;
 
 pub fn str_length(mut args: Args) -> Result<Value> {
     let len = string_arg!(args).len();
@@ -34,3 +35,15 @@ pub fn chr(mut args: Args) -> Result<Value> {
 
     return_string!(output)
 }
+
+pub fn ord(mut args: Args) -> Result<Value> {
+    let input = string_arg!(args);
+
+    if input.is_empty() {
+        return Err(RuntimeError::EmptyList);
+    }
+
+    let output = input.chars().next().unwrap() as u32;
+
+    return_scalar!(output as f64)
+}