1 // Copyright 2025 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #![no_std] 15 #![cfg_attr(test, no_main)] 16 17 use core::ptr::NonNull; 18 19 use foreign_box::ForeignBox; 20 21 pub mod unsafe_list; 22 23 pub use unsafe_list::{Adapter, Link, UnsafeList}; 24 25 pub struct ForeignList<T, A: Adapter> { 26 list: UnsafeList<T, A>, 27 } 28 29 impl<T, A: Adapter> Default for ForeignList<T, A> { default() -> Self30 fn default() -> Self { 31 Self::new() 32 } 33 } 34 35 impl<T, A: Adapter> ForeignList<T, A> { new() -> Self36 pub const fn new() -> Self { 37 Self { 38 list: UnsafeList::new(), 39 } 40 } 41 is_empty(&self) -> bool42 pub fn is_empty(&self) -> bool { 43 unsafe { self.list.is_empty() } 44 } 45 push_front(&mut self, element: ForeignBox<T>)46 pub fn push_front(&mut self, element: ForeignBox<T>) { 47 let element = element.consume(); 48 unsafe { self.list.push_front_unchecked(element.as_ptr()) } 49 } 50 push_back(&mut self, element: ForeignBox<T>)51 pub fn push_back(&mut self, element: ForeignBox<T>) { 52 let element = element.consume(); 53 unsafe { self.list.push_back_unchecked(element.as_ptr()) } 54 } 55 pop_head(&mut self) -> Option<ForeignBox<T>>56 pub fn pop_head(&mut self) -> Option<ForeignBox<T>> { 57 unsafe { 58 self.list 59 .pop_head() 60 .map(|element| ForeignBox::new(NonNull::new_unchecked(element))) 61 } 62 } 63 for_each<E, F: FnMut(&T) -> Result<(), E>>(&self, callback: F) -> Result<(), E>64 pub fn for_each<E, F: FnMut(&T) -> Result<(), E>>(&self, callback: F) -> Result<(), E> { 65 unsafe { self.list.for_each(callback) } 66 } 67 } 68