Parcourir la source

[eval] NativeString.sub

Aleksandr Kuzmenko il y a 4 ans
Parent
commit
2b92f66100
2 fichiers modifiés avec 29 ajouts et 0 suppressions
  1. 18 0
      src/macro/eval/evalStdLib.ml
  2. 11 0
      std/eval/NativeString.hx

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

@@ -3129,6 +3129,23 @@ module StdNativeString = struct
 		let s = decode_native_string v in
 		vint (String.length s)
 	)
+
+	let sub = vfun3 (fun v1 v2 v3 ->
+		let s = decode_native_string v1
+		and start = decode_int v2 in
+		let max_length = String.length s - start in
+		try
+			if v3 = VNull then
+				vnative_string (String.sub s start max_length)
+			else
+				let length =
+					let l = decode_int v3 in
+					if l > max_length then max_length else l
+				in
+				vnative_string (String.sub s start length)
+		with Invalid_argument _ ->
+			throw_string "Invalid arguments for eval.NativeString.sub" null_pos
+	)
 end
 
 let init_fields builtins path static_fields instance_fields =
@@ -3742,6 +3759,7 @@ let init_standard_library builtins =
 		"char",StdNativeString.char;
 		"code",StdNativeString.code;
 		"get_length",StdNativeString.get_length;
+		"sub",StdNativeString.sub;
 	] [];
 	init_fields builtins (["eval";"integers";"_UInt64"],"UInt64_Impl_") EvalIntegers.uint64_fields [];
 	init_fields builtins (["eval";"integers";"_Int64"],"Int64_Impl_") EvalIntegers.int64_fields [];

+ 11 - 0
std/eval/NativeString.hx

@@ -25,6 +25,17 @@ import haxe.io.Bytes;
 	**/
 	public function code(index:Int):Int;
 
+	/**
+		Returns a fresh string up to `length` characters long, containing the
+		substring that starts at position `start`.
+
+		If `length` is not specified the all characters from `start` to the end
+		of this string are returned.
+
+		Throws an exception if `index` is outside of the string bounds.
+	**/
+	public function sub(start:Int, ?length:Int):NativeString;
+
 	public function toString():String;
 
 	public function toBytes():Bytes;