Skip to content

Commit

Permalink
Add String.concat
Browse files Browse the repository at this point in the history
  • Loading branch information
ushitora-anqou committed Jan 6, 2019
1 parent 810901e commit 8cc16ae
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 16 deletions.
51 changes: 35 additions & 16 deletions stdlib.ml
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,6 @@ module Bytes = struct
let to_string bytes = bytes
end

module String = struct
external length : string -> int = "aqaml_string_length"

external get : string -> int -> char = "aqaml_string_get"

external set : string -> int -> char -> unit = "aqaml_string_set"

external create : int -> bytes = "aqaml_string_create"

external sub : string -> int -> int -> string = "aqaml_string_sub"

external blit :
string -> int -> bytes -> int -> int -> unit
= "aqaml_string_blit"
end

module List = struct
let rec length = function _ :: xs -> 1 + length xs | _ -> 0

Expand Down Expand Up @@ -119,6 +103,41 @@ module List = struct
List.rev (aux [] lst)
end

module String = struct
external length : string -> int = "aqaml_string_length"

external get : string -> int -> char = "aqaml_string_get"

external set : string -> int -> char -> unit = "aqaml_string_set"

external create : int -> bytes = "aqaml_string_create"

external sub : string -> int -> int -> string = "aqaml_string_sub"

external blit :
string -> int -> bytes -> int -> int -> unit
= "aqaml_string_blit"

let concat sep = function
| [] -> ""
| lst ->
let seplen = length sep in
let sum_length = List.fold_left (fun acc s -> acc + length s) 0 lst in
let buf =
Bytes.create @@ (sum_length + (seplen * (List.length lst - 1)))
in
let rec aux pos = function
| [] -> ()
| [hd] -> Bytes.blit_string hd 0 buf pos @@ length hd
| hd :: tl ->
let hdlen = length hd in
Bytes.blit_string hd 0 buf pos hdlen ;
Bytes.blit_string sep 0 buf (pos + hdlen) seplen ;
aux (pos + hdlen + seplen) tl
in
aux 0 lst ; Bytes.to_string buf
end

module Buffer = struct
type t = {mutable buf: bytes; mutable len: int}

Expand Down
8 changes: 8 additions & 0 deletions test.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1557,3 +1557,11 @@ test (Buffer.contents buf) "abcdefghi" ;
Buffer.add_string buf "jk" ;
Buffer.add_string buf "lm" ;
test (Buffer.contents buf) "abcdefghijklm"

;;
test (String.concat ";" ["abc"; "def"; "ghi"]) "abc;def;ghi" ;
test (String.concat "." ["abc"; "def"; "ghi"]) "abc.def.ghi" ;
test (String.concat "." ["abc"]) "abc" ;
test (String.concat "." []) "" ;
let string_of_list src = "[" ^ String.concat "; " src ^ "]" in
test (string_of_list ["a"; "b"; "c"]) "[a; b; c]"

0 comments on commit 8cc16ae

Please sign in to comment.