From c463a8be551848f0401c390a2273c7d5a58a6184 Mon Sep 17 00:00:00 2001 From: zihang Date: Wed, 25 Dec 2024 12:07:35 +0800 Subject: [PATCH] fix(deque): avoid content leakage --- deque/deque.mbt | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/deque/deque.mbt b/deque/deque.mbt index 19aec53fc..b9b93af43 100644 --- a/deque/deque.mbt +++ b/deque/deque.mbt @@ -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] { @@ -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 { @@ -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 { @@ -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 { @@ -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 {