Browse Source

[eval] added length, char and code to NativeStirng

Aleksandr Kuzmenko 4 years ago
parent
commit
4f9972d375
2 changed files with 40 additions and 0 deletions
  1. 22 0
      src/macro/eval/evalStdLib.ml
  2. 18 0
      std/eval/NativeString.hx

+ 22 - 0
src/macro/eval/evalStdLib.ml

@@ -3110,6 +3110,25 @@ module StdNativeString = struct
 		and s2 = decode_native_string v2 in
 		vnative_string (s1 ^ s2)
 	)
+
+	let char = vfun2 (fun v1 v2 ->
+		let s = decode_native_string v1
+		and index = decode_int v2 in
+		try encode_string (String.make 1 s.[index])
+		with Invalid_argument s -> throw_string s null_pos
+	)
+
+	let code = vfun2 (fun v1 v2 ->
+		let s = decode_native_string v1
+		and index = decode_int v2 in
+		try vint (int_of_char s.[index])
+		with Invalid_argument s -> throw_string s null_pos
+	)
+
+	let get_length = vfun1 (fun v ->
+		let s = decode_native_string v in
+		vint (String.length s)
+	)
 end
 
 let init_fields builtins path static_fields instance_fields =
@@ -3720,6 +3739,9 @@ let init_standard_library builtins =
 		"toBytes",StdNativeString.to_bytes;
 		"toString",StdNativeString.to_string;
 		"concat",StdNativeString.concat;
+		"char",StdNativeString.char;
+		"code",StdNativeString.code;
+		"get_length",StdNativeString.get_length;
 	] [];
 	init_fields builtins (["eval";"integers";"_UInt64"],"UInt64_Impl_") EvalIntegers.uint64_fields [];
 	init_fields builtins (["eval";"integers";"_Int64"],"Int64_Impl_") EvalIntegers.int64_fields [];

+ 18 - 0
std/eval/NativeString.hx

@@ -3,10 +3,28 @@ package eval;
 import haxe.io.Bytes;
 
 @:coreType abstract NativeString {
+	/** String length */
+	public var length(get,never):Int;
+	function get_length():Int;
+
 	@:from static public function fromString(s:String):NativeString;
 
 	@:from static public function fromBytes(b:Bytes):NativeString;
 
+	/**
+		Returns a character at the specified `index`.
+
+		Throws an exception if `index` is outside of the string bounds.
+	**/
+	public function char(index:Int):String;
+
+	/**
+		Returns a character code at the specified `index`.
+
+		Throws an exception if `index` is outside of the string bounds.
+	**/
+	public function code(index:Int):Int;
+
 	public function toString():String;
 
 	public function toBytes():Bytes;