Skip to content
Draft
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
20 changes: 15 additions & 5 deletions buffer/buffer.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,25 @@ struct Buffer {
}

///|
/// Expand the buffer size if capacity smaller than required space.
fn Buffer::grow_if_necessary(self : Buffer, required : Int) -> Unit {
let start = if self.data.length() <= 0 { 1 } else { self.data.length() }
let enough_space = for space = start {
/// Smallest capacity reached by repeatedly doubling `current` until it
/// covers `required`. Doubling a capacity past 2^30 overflows Int (and can
/// loop forever, e.g. 2^30 -> INT_MIN -> 0 -> 0); when that happens, fall
/// back to exactly `required`.
fn grow_capacity(current : Int, required : Int) -> Int {
for space = current {
if space >= required {
break space
}
continue space * 2
let doubled = space * 2
continue if doubled > 0 { doubled } else { required }
}
}

///|
/// Expand the buffer size if capacity smaller than required space.
fn Buffer::grow_if_necessary(self : Buffer, required : Int) -> Unit {
let start = if self.data.length() <= 0 { 1 } else { self.data.length() }
let enough_space = grow_capacity(start, required)
if enough_space != self.data.length() {
let new_data = FixedArray::make_and_blit(
self.data,
Expand Down
31 changes: 31 additions & 0 deletions buffer/grow_wbtest.mbt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2026 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 "grow_capacity doubles until the requirement is covered" {
inspect(grow_capacity(1, 100), content="128")
inspect(grow_capacity(3, 24), content="24")
inspect(grow_capacity(16, 16), content="16")
inspect(grow_capacity(16, 17), content="32")
}

///|
test "grow_capacity survives Int overflow instead of looping forever" {
// 2^30 doubles to INT_MIN; the old loop then went 0 -> 0 -> ... forever.
let big = 1 << 30
inspect(grow_capacity(big, big + 1) == big + 1, content="true")
// A non-power-of-two start overflows to a negative value on the way up;
// the fallback allocates exactly the requirement.
inspect(grow_capacity(11, 1_500_000_000), content="1500000000")
}
Loading