0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
d33tah
  • 10,999
  • 13
  • 68
  • 158
  • It looks like your question might be answered by the answers of [Need holistic explanation about Rust's cell and reference counted types](https://stackoverflow.com/q/45674479/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. [The duplicate applied to your situation](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=18f9dad7b69ec53fa2f823dea58ece22) – Shepmaster Jan 03 '20 at 21:50
  • 1
    Please don't take this the wrong way, but if you aren't yet familiar with fundamental Rust concepts like interior mutability, writing a custom allocator in Rust may not be an appropriately-sized project. – Shepmaster Jan 03 '20 at 21:51
  • Please do not use leading underscores for variables that are used. Leading underscores indicate that a variable is **deliberately left unused**. – Shepmaster Jan 03 '20 at 21:52
  • 1
    *can't see what part specifically makes it possible* — the data is inside a mutex that is subsequently locked. – Shepmaster Jan 03 '20 at 21:56

0 Answers0