Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use StringBuilder instead of Buffer in builtin and json package #550

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion builtin/assert.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
// limitations under the License.

fn debug_string[T : Show](t : T) -> String {
let buf = Buffer::new(size_hint=50)
let buf = StringBuilder::new(size_hint=50)
t.output(buf)
buf.to_string()
}
Expand Down
2 changes: 1 addition & 1 deletion builtin/autoloc.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn ArgsLoc::to_string(self : ArgsLoc) -> String {
}

pub fn ArgsLoc::to_json(self : ArgsLoc) -> String {
let buf = Buffer::new(size_hint=10)
let buf = StringBuilder::new(size_hint=10)
buf.write_char('[')
for i = 0; i < self._.length(); i = i + 1 {
if i != 0 {
Expand Down
2 changes: 1 addition & 1 deletion builtin/buffer.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ pub fn write_string(self : Buffer, value : String) -> Unit {
}

pub fn write_object(self : Buffer, value : Show) -> Unit {
write_string(self, value.to_string())
self.write_string(value.to_string())
}

pub fn write_bytes(self : Buffer, value : Bytes) -> Unit {
Expand Down
10 changes: 10 additions & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,15 @@ impl SourceLoc {
to_string(Self) -> String
}

type StringBuilder
impl StringBuilder {
new(~size_hint : Int = ..) -> Self
to_string(Self) -> String
write_char(Self, Char) -> Unit
write_string(Self, String) -> Unit
write_sub_string(Self, String, Int, Int) -> Unit
}

pub type UnsafeMaybeUninit
impl Unit {
op_equal(Unit, Unit) -> Bool
Expand Down Expand Up @@ -536,6 +545,7 @@ impl String {
op_add(String, String) -> String
op_equal(String, String) -> Bool
op_get(String, Int) -> Char
substring(String, ~start : Int = .., ~end : Int = ..) -> String
to_js_string(String) -> Js_string
to_json(String) -> Json
to_string(String) -> String
Expand Down
8 changes: 4 additions & 4 deletions builtin/console.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn to_string(self : Int64) -> String {
// The min and max value of i64 are -9223372036854775808 and 9223372036854775807,
// so max=20 is enough.

let buf = Buffer::new(size_hint=20)
let buf = StringBuilder::new(size_hint=20)
if self < 0L {
buf.write_char('-')
}
Expand Down Expand Up @@ -71,7 +71,7 @@ pub fn to_string(self : Int) -> String {
// The min and max value of i32 are -2147483648 and 2147483647,
// so max=11 is enough.

let buf = Buffer::new()
let buf = StringBuilder::new()
if self < 0 {
buf.write_char('-')
}
Expand All @@ -88,7 +88,7 @@ pub fn to_string(self : Int) -> String {
}

pub fn UInt::to_string(self : UInt) -> String {
let buf = Buffer::new()
let buf = StringBuilder::new()
fn write_digits(num) {
let num2 = num / 10U
if num2 != 0U {
Expand All @@ -108,7 +108,7 @@ test "UInt::to_string" {
}

pub fn UInt64::to_string(self : UInt64) -> String {
let buf = Buffer::new()
let buf = StringBuilder::new()
fn write_digits(num : UInt64) {
let num2 = num / 10UL
if num2 != 0UL {
Expand Down
2 changes: 1 addition & 1 deletion builtin/json.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ fn escape_json_string(str : String) -> String {
}

let len = str.length()
let buf = Buffer::new(size_hint=len)
let buf = StringBuilder::new(size_hint=len)
for i in 0..<len {
let c = str[i]
match c {
Expand Down
2 changes: 1 addition & 1 deletion builtin/linked_hash_map.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ fn calc_grow_threshold(capacity : Int) -> Int {
// Utils

fn debug_entries[K : Show, V : Show](self : Map[K, V]) -> String {
let buf = Buffer::new()
let buf = StringBuilder::new()
for i = 0; i < self.entries.length(); i = i + 1 {
if i > 0 {
buf.write_char(',')
Expand Down
4 changes: 3 additions & 1 deletion builtin/moon.pkg.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"int64_nonjs.mbt": ["not", "js"],
"arraycore_js.mbt": ["js"],
"arraycore_nonjs.mbt": ["not", "js"],
"array_nonjs_test.mbt": ["not", "js"]
"array_nonjs_test.mbt": ["not", "js"],
"stringbuilder_buffer.mbt": ["not", ["js"]],
"stringbuilder_concat.mbt": ["js"]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mark todo: add wasm-gc here once we have support for jsstring proposal on wasm-gc

}
}
4 changes: 2 additions & 2 deletions builtin/show.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub impl Show for Bytes with output(self, logger) {
}

pub impl Show for Bytes with to_string(self) {
let buf = Buffer::new()
let buf = StringBuilder::new()
Show::output(self, buf)
buf.to_string()
}
Expand Down Expand Up @@ -128,7 +128,7 @@ pub impl Show for String with to_string(self) { self }
/// Returns a valid MoonBit string literal representation of a string,
/// add quotes and escape special characters.
pub fn escape(self : String) -> String {
let buf = Buffer::new()
let buf = StringBuilder::new()
Show::output(self, buf)
buf.to_string()
}
Expand Down
44 changes: 44 additions & 0 deletions builtin/string.mbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2024 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/// @intrinsic %string.substring
fn unsafe_substring(str : String, start : Int, end : Int) -> String {
let len = end - start
let buf = Buffer::new(size_hint=len)
buf.write_sub_string(str, start, len)
buf.to_string()
}

/// Get substring of the string from [start] to [end] exclusive.
pub fn substring(
self : String,
~start : Int = 0,
~end : Int = self.length()
) -> String {
if start < 0 {
abort("String::substring: start index is negative")
}
if end < 0 {
abort("String::substring: end index is negative")
}
if start > end {
abort("String::substring: start index is greater than end index")
}
if end > self.length() {
abort(
"String::substring: end index is greater than the length of the string",
)
}
unsafe_substring(self, start, end)
}
23 changes: 23 additions & 0 deletions builtin/string_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,26 @@ test "String::escape" {
,
)
}

test "substring" {
assert_eq!("abc".substring(), "abc")
assert_eq!("abc".substring(start=1), "bc")
assert_eq!("abc".substring(end=2), "ab")
assert_eq!("abc".substring(start=1, end=2), "b")
}

test "panic substring_start_index_error" {
"test".substring(start=-1, end=0) |> ignore
}

test "panic substring_end_index_error" {
"test".substring(start=0, end=-1) |> ignore
}

test "panic substring_start_end_index_error" {
"test".substring(start=1, end=0) |> ignore
}

test "panic substring_length_index_error" {
"test".substring(start=0, end=5) |> ignore
}
40 changes: 40 additions & 0 deletions builtin/stringbuilder_buffer.mbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright 2024 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

type StringBuilder Buffer

pub fn StringBuilder::new(~size_hint : Int = 0) -> StringBuilder {
Buffer::new(~size_hint)
}

pub fn StringBuilder::write_string(self : StringBuilder, str : String) -> Unit {
self._.write_string(str)
}

pub fn StringBuilder::write_char(self : StringBuilder, ch : Char) -> Unit {
self._.write_char(ch)
}

pub fn StringBuilder::write_sub_string(
self : StringBuilder,
str : String,
start : Int,
len : Int
) -> Unit {
self._.write_sub_string(str, start, len)
}

pub fn StringBuilder::to_string(self : StringBuilder) -> String {
self._.to_string()
}
41 changes: 41 additions & 0 deletions builtin/stringbuilder_concat.mbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright 2024 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

type StringBuilder Ref[String]

pub fn StringBuilder::new(~size_hint : Int = 0) -> StringBuilder {
ignore(size_hint)
{ val: "" }
}

pub fn StringBuilder::write_string(self : StringBuilder, str : String) -> Unit {
self.val += str
}

pub fn StringBuilder::write_char(self : StringBuilder, ch : Char) -> Unit {
self.val += Char::to_string(ch)
}

pub fn StringBuilder::write_sub_string(
self : StringBuilder,
str : String,
start : Int,
len : Int
) -> Unit {
self.val += str.substring(~start, end=start + len)
}

pub fn StringBuilder::to_string(self : StringBuilder) -> String {
self.val
}
21 changes: 21 additions & 0 deletions builtin/stringbuilder_test.mbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright 2024 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

test "stringbuilder" {
let buf = StringBuilder::new()
buf.write_string("hello")
buf.write_char(' ')
buf.write_sub_string("world", 0, 3)
inspect!(buf.to_string(), content="hello wor")
}
2 changes: 1 addition & 1 deletion builtin/traits.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub trait Show {

// Default implementation for `Show::to_string`, uses a `Buffer`
impl Show with to_string(self) {
let logger = Buffer::new()
let logger = StringBuilder::new()
self.output(logger)
logger.to_string()
}
Expand Down
37 changes: 0 additions & 37 deletions json/internal_types.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -61,40 +61,3 @@ priv enum Token {
Comma
Colon
} derive(Eq, Show)

priv struct StringBuilder {
mut buffer : String
}

fn StringBuilder::make() -> StringBuilder {
{ buffer: "" }
}

fn add_string(self : StringBuilder, s : String) -> Unit {
self.buffer = self.buffer + s
}

fn add_substring(
self : StringBuilder,
s : String,
start : Int,
end : Int
) -> Unit {
self.buffer = self.buffer + s.substring(~start, ~end)
}

fn add_char(self : StringBuilder, c : Char) -> Unit {
self.buffer = self.buffer + c.to_string()
}

fn to_string(self : StringBuilder) -> String {
self.buffer
}

test "add_string method coverage" {
let sb = StringBuilder::make()
add_string(sb, "Hello")
assert_eq!(sb.buffer, "Hello")
add_string(sb, " World")
assert_eq!(sb.buffer, "Hello World")
}
8 changes: 4 additions & 4 deletions json/json.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ pub fn stringify(
if members.is_empty() {
return "{}"
}
let buf = Buffer::new(size_hint=0)
let buf = StringBuilder::new(size_hint=0)
buf.write_char('{')
buf.write_string(indent_str(level + 1, indent))
let mut first = true
Expand Down Expand Up @@ -125,7 +125,7 @@ pub fn stringify(
if arr.is_empty() {
return "[]"
}
let buf = Buffer::new(size_hint=0)
let buf = StringBuilder::new(size_hint=0)
buf.write_char('[')
buf.write_string(indent_str(level + 1, indent))
for i, v in arr {
Expand All @@ -139,7 +139,7 @@ pub fn stringify(
buf..write_char(']').to_string()
}
String(s) => {
let buf = Buffer::new(size_hint=0)
let buf = StringBuilder::new(size_hint=0)
buf
..write_char('\"')
..write_string(escape(s, ~escape_slash))
Expand All @@ -165,7 +165,7 @@ fn escape(str : String, ~escape_slash : Bool) -> String {
}
}

let buf = Buffer::new(size_hint=str.length())
let buf = StringBuilder::new(size_hint=str.length())
for c in str {
match c {
'"' | '\\' => buf.write_string("\\\{c}")
Expand Down
Loading