0

The following code gets the page size from sysconf to optimally read files from the filesystem. I am unable to create the buffer with the size:

lazy_static! {
    static ref PAGE_SIZE: i64 = sysconf(SysconfVariable::ScPagesize).unwrap();
}

fn main() {
    let mut buffer = [0; *PAGE_SIZE as usize];
}

Gives me:

error[E0080]: constant evaluation error
  --> src/main.rs:6:30
   |
6  |         let mut buffer = [0; *PAGE_SIZE as usize];
   |                              ^^^^^^^^^^ unimplemented constant expression: deref operation

I thought it is a operator priority problem and tried to wrap with it braces but the result still the same:

error[E0080]: constant evaluation error
  --> src/main.rs:6:30
   |
6  |         let mut buffer = [0; (*(PAGE_SIZE)) as usize];
   |                              ^^^^^^^^^^^^^^ unimplemented constant expression: deref operation

How to use the constant above for allocating a buffer?

1 Answer 1

2

This is not compile-time constant at all. Use vec! for anything that can't be determined compile-time:

let mut buffer = vec![0; *PAGE_SIZE as usize];

Currently there's no compiler level support for Variable-Length Arrays (VLA).

Sign up to request clarification or add additional context in comments.

3 Comments

Okay, this is not a compile-time constant. The docs also say so. Is there any other way to read page size once and to use it everywhere? Is there any way to write page size into a real compile-time constant? static PAGE_SIZE: i64 = ... maybe? Anything?
You can achieve that via a compiler plugin, or build script combined with env!. I cannot recommend allocating on stack, because allocating a page on stack may cause overflow.
@TatsuyukiIshi: I would like to note that using a build script and env! should be done carefully in the event of cross-compiling. The target and host systems may have different page sizes. Thus, I would instead suggest using cfg.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.