1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 */ 19 20 #[cfg(target_env = "sgx")] 21 use alloc::alloc::{self, Layout, LayoutErr}; 22 #[cfg(not(target_env = "sgx"))] 23 use std::alloc::{self, Layout, LayoutErr}; 24 25 const DEFAULT_ALIGN_BYTES: usize = 4; 26 27 #[derive(PartialEq, Eq)] 28 pub struct Allocation { 29 layout: Layout, 30 ptr: *mut u8, 31 } 32 33 impl Allocation { 34 /// Allocates a chunk of memory of `size` bytes with optional alignment. new(size: usize, align: Option<usize>) -> Result<Self, LayoutErr>35 pub fn new(size: usize, align: Option<usize>) -> Result<Self, LayoutErr> { 36 let alignment = align.unwrap_or(DEFAULT_ALIGN_BYTES); 37 let layout = Layout::from_size_align(size, alignment)?; 38 let ptr = unsafe { alloc::alloc(layout.clone()) }; 39 if ptr.is_null() { 40 alloc::handle_alloc_error(layout); 41 } 42 Ok(Self { 43 ptr: ptr, 44 layout: layout, 45 }) 46 } 47 as_mut_ptr(&self) -> *mut u848 pub fn as_mut_ptr(&self) -> *mut u8 { 49 self.ptr 50 } 51 52 /// Returns the size of the Allocation in bytes. size(&self) -> usize53 pub fn size(&self) -> usize { 54 self.layout.size() 55 } 56 57 /// Returns the byte alignment of the Allocation. align(&self) -> usize58 pub fn align(&self) -> usize { 59 self.layout.align() 60 } 61 } 62 63 impl Drop for Allocation { drop(&mut self)64 fn drop(&mut self) { 65 unsafe { 66 alloc::dealloc(self.ptr, self.layout.clone()); 67 } 68 } 69 } 70