I'm trying to write my own custom global allocator that will need to keep some state. Consider the following non-compiling code:
#![feature(rustc_private)]
use std::alloc::{GlobalAlloc, Layout};
extern crate libc;
struct MyAllocator {
offset: usize,
}
unsafe impl GlobalAlloc for MyAllocator {
unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
let ret = libc::malloc(_layout.size() as libc::size_t) as *mut u8;
self.offset += _layout.size() as usize;
ret
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}
}
#[global_allocator]
static A: MyAllocator = MyAllocator { offset: 0 };
fn main() {
println!("it runs!");
}
I'm getting the following error:
error[E0594]: cannot assign to `self.offset` which is behind a `&` reference
--> src/main.rs:14:9
|
12 | unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
| ----- help: consider changing this to be a mutable reference: `&mut self`
13 | let ret = libc::malloc(_layout.size() as libc::size_t) as *mut u8;
14 | self.offset += _layout.size() as usize;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written
How to solve this one? I can see some example code in this repository, but can't see what part specifically makes it possible to convert &self
to &mut self
.