Skip to content

Commit

Permalink
fix(deque): avoid content leakage
Browse files Browse the repository at this point in the history
  • Loading branch information
peter-jerry-ye committed Dec 25, 2024
1 parent 7425f1f commit c463a8b
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions deque/deque.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

///|
fn set_null[T](buffer : UninitializedArray[T], index : Int) = "%fixedarray.set_null"

///|
/// Creates a new, empty deque.
pub fn T::new[A](capacity~ : Int = 0) -> T[A] {
Expand Down Expand Up @@ -199,8 +202,12 @@ pub fn push_back[A](self : T[A], value : A) -> Unit {
pub fn unsafe_pop_front[A](self : T[A]) -> Unit {
match self.len {
0 => abort("The deque is empty!")
1 => self.len -= 1
1 => {
set_null(self.buf, self.head)
self.len -= 1
}
_ => {
set_null(self.buf, self.head)
self.head = if self.head < self.buf.length() - 1 {
self.head + 1
} else {
Expand Down Expand Up @@ -230,8 +237,12 @@ pub fn pop_front_exn[A](self : T[A]) -> Unit {
pub fn unsafe_pop_back[A](self : T[A]) -> Unit {
match self.len {
0 => abort("The deque is empty!")
1 => self.len -= 1
1 => {
set_null(self.buf, self.tail)
self.len -= 1
}
_ => {
set_null(self.buf, self.tail)
self.tail = if self.tail > 0 {
self.tail - 1
} else {
Expand Down Expand Up @@ -260,11 +271,14 @@ pub fn pop_front[A](self : T[A]) -> A? {
match self.len {
0 => None
1 => {
let origin_head = self.buf[self.head]
set_null(self.buf, self.head)
self.len -= 1
Some(self.buf[self.head])
Some(origin_head)
}
_ => {
let origin_head = self.head
set_null(self.buf, self.head)
self.head = if self.head < self.buf.length() - 1 {
self.head + 1
} else {
Expand All @@ -288,11 +302,14 @@ pub fn pop_back[A](self : T[A]) -> A? {
match self.len {
0 => None
1 => {
let origin_back = self.buf[self.tail]
set_null(self.buf, self.tail)
self.len -= 1
Some(self.buf[self.tail])
Some(origin_back)
}
_ => {
let origin_back = self.tail
set_null(self.buf, self.tail)
self.tail = if self.tail > 0 {
self.tail - 1
} else {
Expand Down

0 comments on commit c463a8b

Please sign in to comment.