Skip to content

How to override Math.random with a global template? #1648

@DanielSidhion

Description

@DanielSidhion

This isn't strictly rusty_v8, but it's been hard to find any resources on this, so I thought I'd start here since you folks might be able to help.

Is there any way I can override the Math.random function with a global object template? By this I mean I want to provide an object_template in the ContextOptions when creating a context that defines a Math.random. I've already figured out that that I can (and how to) override Math.random after the context is created, but ideally I'd be able to bundle this work in the same global template, since I'm already using it for other things (side question: does it matter performance-wise to provide a global object template when creating the context, or modifying the global object after creating the context?).

Here's some code that I tried, but the result shows that Math.random wasn't overridden:

fn custom_random(
    scope: &mut v8::HandleScope,
    args: v8::FunctionCallbackArguments,
    mut retval: v8::ReturnValue,
) {
    retval.set(v8::Number::new(scope, 42).into());
}
let isolate = &mut v8::Isolate::new(Default::default());
let scope = &mut v8::HandleScope::new(isolate);

let global = v8::ObjectTemplate::new(scope);
let random_fn = v8::FunctionTemplate::new(scope, custom_random);
let math_obj = v8::ObjectTemplate::new(scope);
math_obj.set(
    v8::String::new(scope, "random").unwrap().into(),
    random_fn.into(),
);
global.set(
    v8::String::new(scope, "Math").unwrap().into(),
    math_obj.into(),
);

let context = v8::Context::new(
    scope,
    v8::ContextOptions {
        global_template: Some(global),
        ..Default::default()
    },
);

let scope = &mut v8::ContextScope::new(scope, context);
let code = v8::String::new(scope, "Math.random()").unwrap();
let script = v8::Script::compile(scope, code, None).unwrap();
let result = script.run(scope).unwrap();
println!("result: {}", result.to_rust_string_lossy(scope));
// Prints "result: 0.7939112874678715", and not "result: 42"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions