How do I use the rand crate without the standard library? - random

I'm doing embedded game development for the Sega Megadrive with Rust and would like a random number generator to increase replayability. It can be pseudo-random: there's no security stuff required.
I've been looking at the rand crate which falls in the "No standard library" department, but I'm not sure on how to use it with this in my Crate.toml:
[dependencies]
rand = {version = "0.8.3", default-features = false}
When I disable default-features, there's no random function in the prelude anymore. There is the Rng trait but I'm too inexperienced to figure out how to use it.

To use the rand crate without std you need to manually use one of the generators that work without it. Those generators are the OsRng and the SmallRng structs. As the name suggests the first one uses the operating system's generator, which requires the getrandom crate, which probably isn't supported on SEGA Megadrive.
SmallRng should work without problems though. We cannot use the random() function, we need to manually create the generator and then call its methods.
To do this we first have to create a generator, like this:
let mut small_rng = SmallRng::seed_from_u64([insert your seed here]);
You can also use the seed_from_u32, whose documentation you can find here.
Then we can use it as such:
let rand_num = small_rng.next_u64();
Importantly, we have to import the RngCore trait to use these functions, this way:
use rand::{Rng, SeedableRng};
use rand::rngs::SmallRng;
use rand::RngCore;
SmallRng relies on the small_rng crate feature, so you should import it this way (in the Cargo.toml file):
rand = { version = "0.8.3", features = ["small_rng"], default-features = false }
I should also leave a disclaimer: SmallRng's generator isn't cryptographically secure.

Related

Is there a way to use a dynamic function name in Elixir from string interpolation like in Ruby?

I want to be able to construct a function call from a string in elixir. Is this possible? The equivalent ruby method call would be:
"uppercase".send("u#{:pcase}")
Although the answer by #fhdhsni is perfectly correct, I’d add some nitpicking clarification.
The exact equivalent of Kernel#send from ruby in elixir is impossible, because Kernel#send allows to call private methods on the receiver. In elixir, private functions do not ever exist in the compiled code.
If you meant Kernel#public_send, it might be achieved with Kernel.apply/3, as mentioned by #fhdhsni. The only correction is since the atom table is not garbage collected, and one surely wants to call an indeed existing function, it should be done with String.to_existing_atom/1.
apply(
String,
String.to_existing_atom("u#{:pcase}"),
["uppercase"]
)
Also, one might use macros during the compilation stage to generate respective clauses when the list of functions to call is predictable (when it’s not, the code already smells.)
defmodule Helper do
Enum.each(~w|upcase|a, fn fname ->
def unquote(fname)(param),
do: String.unquote(fname)(param)
# or
# defdelegate unquote(fname)(param), to: String
end)
end
Helper.upcase("uppercase")
#⇒ "UPPERCASE"
In Elixir module and function names are atoms. You can use apply to call them dynamically.
apply(String, String.to_atom("u#{:pcase}"), ["uppercase"]) # "UPPERCASE"
Depending on your use case it might not be a good idea to create atoms dynamically (since the atom table is not garbage collected).

Return Ruby's Fiddle::Pointer from C function

I am currently working on a high-performance Vector/Matrix Ruby gem C extension, as I find the built-in implementation cumbersome and not ideal for most cases that I have personally encountered, as well as lacking in other areas.
My first approach was implementing in Ruby as a subclass of Fiddle::CStructEntity, as a goal is to make them optimized for interop without need for conversion (such as passing to native OpenGL functions). Implementing in C offers a great benefit for the math, but I ran into a roadblock when trying to implement a minor function.
I wished to have a method return a Fiddle::Pointer to the struct (basically a pointer to Rdata->data. I wished to return an actual Fiddle::Pointer object. Returning an integer address, packed string, etc. is trivial, and using that could easily be extended in a Ruby method to convert to a Fiddle::Pointer like this:
def ptr
# Assume address is an integer address returned from C
Fiddle::Pointer.new(self.address, self.size)
end
This kind of opened up a question to me, and that is it possible to to even do such from C? Fiddle is not part of the core, library, it is part of the standard lib, and as such, is really just an extension itself.
The problem is trivial, and can be easily overcome with a couple lines of Ruby code as demonstrated above, but was more curious if returning a Fiddle object was even possible from a C extension without hacks? I was unable to find any examples of this being done, and as always when it comes to the documentation involving Fiddle, it is quite basic and does not explain much.
The solution for this is actually rather simple, though admittedly not as elegant or clean of a solution I was hoping to discover.
There are possibly more elaborate ways to go about this by including the headers for Fiddle, and building against it, but this was not really a viable solution, as I didn't want to restrict my C extension to only work with Ruby 2.0+, and would be perfectly acceptable to simply omit the method in the event Ruby version was less than 2.0.
First I include version.h, which gives access defines the macro RUBY_API_VERSION_MAJOR, which is all I really need to know in regards to whether or not Fiddle will be present or not.
This will be an abbreviated version to simply show how to get the Fiddle::Pointer class as a VALUE, and to create an instance.
#if RUBY_API_VERSION_MAJOR >= 2
rb_require("fiddle");
VALUE fiddle = rb_const_get(rb_cObject, rb_intern("Fiddle"));
rb_cFiddlePointer = rb_const_get(fiddle, rb_intern("Pointer"));
#endif
In this example, the class is stored in rb_cFiddlePointer, which can then be used to create and return a Fiddle::Pointer object from C.
// Get basic data about the struct
struct RData *rdata = RDATA(self);
VALUE *args = xmalloc(sizeof(VALUE) * 2);
// Set the platform pointer-size address (could just use size_t here...)
#if SIZEOF_INTPTR_T == 4
args[0] = LONG2NUM((long) rdata->data);
#elif SIZEOF_INTPTR_T == 8
args[0] = LL2NUM((long long) rdata->data);
#else
args[0] = INT2NUM(0);
#endif
// Get size of structure
args[1] = INT2NUM(SIZE_OF_YOUR_STRUCTURE);
VALUE ptr = rb_class_new_instance(2, args, rb_cFiddlePointer);
xfree(args);
return ptr;
After linking the function to an actual Ruby method, you can then call it to get a sized pointer to the internal structure in memory.

Library to compare two .proto files for equal message ids

In my current project, I am persisting protobufs with enums. To ensure backwards compatibility, I need to make sure that these enums stay the same and I want to write unit tests for that.
Example:
legacy_mood.proto:
enum Mood {
HAPPY = 0;
SAD = 1;
}
mood.proto:
enum Mood {
EXCITED = 0;
HAPPY = 1;
SAD = 2;
}
I am looking for a way to compare these two protos, and in this case let the test fail, because the constant value from HAPPY and SAD changed.
I want to allow new values, so I really just want to check equivalence for elements that exist in the legacy proto, so EXCITED should be ignored in this case.
Before I implement this myself, is there a library for that? I've been googleing for a bit now, but couldn't find anything. Could be in Java, C++ or Python
In any of the language you mentioned, you can convert the Enum value A in message Foo to its string representation, and use the string name to get the Enum value B in message Bar, and make sure the two values are equal.
Python API: https://developers.google.com/protocol-buffers/docs/reference/python-generated#enum

Random function in Modelica

Hello,I need a function as random in C language. Maybe you will say that i can call C function, but the effect is not the same in visual c++ tool. So, I need your help.
thanks.
See the Noise library:
https://github.com/DLR-SR/Noise
It has some models and functions to generate random numbers.
If you are using Dymola, you can use the function rand():
model rand_model
Real a(start=rand());
Real b(start=rand());
equation
when (sample(1,1)) then
a = rand();
b = rand();
end when;
end rand_model;
The function is not documented in the Dymola user manual and it is no part of the modelica standard. The output seems to be an integer between 0 and 32767, seed seems to be constant.
Perhaps the implementation is given in the moutil.c file which is shipped with Dymola. But i'm not sure.

random number generator in boost.python

How can I use the same random number generator in my "Python with numpy" code as my C++0x code?
I am currently using
std::ranlux64_base_01
in C++ and
numpy.random.RandomState(10)
in Python.
I exposed C++'s random number generator:
typedef std::ranlux64_base_01 RNG;
RNG g_rng;
...
class_<RNG>("RNG");
scope().attr("g_rng") = g_rng;
How do I use it with Python's methods that take a numpy.random?
There are 2 ways:
the first is to use pythons random number generator from c++. It will probably look something like this:
boost::python::object randmod = boost::python::import("numpy.random")
boost::python::object randfunc = randmod.attr("RandomState")
randfunc(10)
The second is to wrap and expose the c++ function so that it can be used from python. The code for this is left an an exercise for the student.
Edit:
Once you have exported the c++ function you would have to make a python object that mimics the interface of numpy.random.RandomState using the c++ function for it's random bits. This is probably more work then you want to do. I have not used numpy, but from the docs it looks like the RandomState object is not-trivial.

Resources