Skip to content

Commit

Permalink
std::strings: add StrBuilder
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Aug 2, 2024
1 parent bb06ca0 commit cdb1928
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions std/strings/builder.jule
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2023-2024 The Jule Programming Language.
// Use of this source code is governed by a BSD 3-Clause
// license that can be found in the LICENSE file.

use utf8 for std::unicode::utf8
use nosafe for std::internal::nosafe

// String builder for efficient concatenation.
struct StrBuilder {
buf: []byte
}

impl StrBuilder {
// Returns new string builder with capacity.
static fn New(cap: int): StrBuilder {
if cap < 0 {
panic("std::strings: StrBuilder.New: cap < 0")
}
ret StrBuilder{
buf: make([]byte, 0, cap)
}
}

// Writes bytes to buffer.
fn Write(mut self, b: []byte) {
self.buf = append(self.buf, b...)
}

// Writes bytes to buffer.
fn WriteStr(mut self, s: str) {
self.buf = append(self.buf, nosafe::Stobs(s)...)
}

// Writes byte to buffer.
fn WriteByte(mut self, b: byte) {
self.buf = append(self.buf, b)
}

// Writes rune into buffer.
fn WriteRune(mut self, r: rune) {
if r < utf8::RuneSelf { // ASCII, fast way.
self.buf = append(self.buf, byte(r))
ret
}
self.WriteStr(str(r))
}

// Returns as string.
fn Str(self): str {
ret str(self.buf)
}

// Returns mutable buffer.
unsafe fn Buf(self): []byte {
ret self.buf
}
}

0 comments on commit cdb1928

Please sign in to comment.