Can I use $urandom_range with time variables? - verilog

I wanted to know if I can simply write:
time time_var;
time_var = $urandom_range (10ms, 7ms);
I've tried using it directly, and there are no errors/warnings issued.
However, the returned value is not between 7-10ms.
I guess it's legal to use $urandom_range with time literals, since I didn't receive any errors. But, why can't I get a value in the proper range?

The IEEE Std (1800-2009) declares the arguments to $urandom_range to be of type int unsigned which is not the same as time. I don't think you can rely on the system function to behave predictably even if you are not getting errors or warnings from your simulator.
It is a compile error in VCS and a warning with Incisive.
Can you use something like this?
int unsigned del = $urandom_range(10, 7);
#(1ms * del);

Related

How to create a very large (more than INT_MAX) character buffer?

I am dealing with very large files, frequently over 2GBs, and need to dump them into a buffer to be able to deal with them.
I create the buffer like this:
char* bigBuffer = nullptr;
...
bigBuffer = new char[3'000'000'000];
The line that allocates the memory shows the following warning when all warnings are enabled: C4310 cast truncates constant value
I tried explicitly telling the compiler this is not an int by changing the line to:
bigBuffer = new char[3'000'000'000ull];
but I'm still getting the same warning. Seems like it is casting it implicitly to an int no matter what.
How do I get the compiler to allow me to create this array in the way I want, or even larger if needed?
I am on the latest version of Visual Studio 2019.

python type hinting not generating error for wrong type

I was recently checking about type hinting and after reading some theory I tried an simple example as below
def myfun(num1: int, num2: int) -> int:
return str(num1) + num2
a = myfun(1,'abc')
print(a)
# output -> 1abc
Here you can see that I have define num1 and num2 of type int and even after passing num2 value as string it is not generating any error.
Also the function should expect to return int type value but it's not complaining on returning string type value.
Can someone please explain what's going wrong here?
It's called type hinting for a reason: you're giving a hint about what a variable should be to the IDE or to anyone else reading your code. At runtime, the type hints don't actually mean anything - they exist for documentation and usability by other developers. If you go against the type hints, python won't stop you (it assumes you know what you're doing), but it's poor practice.
Note that this differs from statically-typed languages like Java, where trying to pass an argument that's incompatible with the function's definition will produce a compile-time error, and if you pass a differently-typed but compatible argument (e.g. passing a float to a function that expects an int) it will be automatically typecast.
Note that the code you've given will encounter a TypeError if the programmer uses it like they're supposed to, because int cannot be concatenated to a str. Your IDE or linter should be able to see this and give you a warning on that line, which it does based on the type hints. That's what the type hints are for - informing the behavior of the IDE and documentation, and providing a red flag that you might not be using a function in the intended way - not anything at runtime.

Writing a raw binary structure to file in D?

I'm trying to have a binary file which contains several binary records defined in some struct. However, I do cannot seem to find how to do it. Looking at other examples, I've managed to write strings without problems, but not struct. I just want to write it like I would in C with fwrite(3), but in D version 2.
Here is what I've tried so far:
using stream.write(tr) - writes human readable/debug representation
using stream.rawWrite(tr) - this sounded like what I need, but fails to compile with:
Error: template std.stdio.File.rawWrite cannot deduce function from
argument types !()(TitleRecord), candidates are:
/usr/lib/ldc/x86_64-linux-gnu/include/d/std/stdio.d(1132): std.stdio.File.rawWrite(T)(in T[] buffer)
trying rawWrite as above, but casting data to various things, also never compiles.
even trying to get back to C with fwrite, but can't get deep enough to get file descriptor I need.
Reading the docs has not been very helpful (writing strings works for me too, but not writing struct). I'm sure there must be simple way to do it, but I'm not able to find it.... Other SO questions did not help me. I D 1.0, it might have been accomplished with stream.writeExact(&tr, tr.sizeof) but that is no longer an option.
import std.stdio;
struct TitleRecord {
short id;
char[49] text;
};
TitleRecord tr;
void main()
{
auto stream = File("filename.dat","wb+");
tr.id = 1234;
tr.text = "hello world";
writeln(tr);
//stream.write(tr);
//stream.rawWrite(tr);
//stream.rawWrite(cast(ubyte[52]) tr);
//stream.rawWrite(cast(ubyte[]) tr);
//fwrite(&tr, 4, 1, stream);
}
For this that error is saying it expects an array not a struct. So one easy way to do it is to simply slice a pointer and give that to rawWrite:
stream.rawWrite((&tr)[0 .. 1]);
The (&tr) gets the address, thus converting your struct to a pointer. Then the [0 .. 1] means get a slice of it from the beginning, grabbing just one element.
Thus you now have a T[] that rawWrite can handle containing your one element.
Be warned if you use the #safe annotation this will not pass, you'd have to mark it #trusted. Also of course any references inside your struct (including string) will be written as binary pointers instead of data as you surely know from C experience. But in the case you showed there you're fine.
edit: BTW you could also just use fwrite if you like, copy/pasting the same code over from C (except it is foo.sizeof instead of sizeof foo). The D File thing is just a small wrapper around C's FILE* and you can get the original FILE* back out to pass to the other functions with stream.getFP() http://dpldocs.info/experimental-docs/std.stdio.File.getFP.html )
rawWrite expects an array, but there are many workarounds.
One is to create a single element array.
file.rawWrite([myStruct]);
Another one is casting the struct into an array. My library called bitleveld has a function for that called reinterpretAsArray. This also makes it easy to create checksums of said structs.
Once in a while I've encountered issues with alignment using this method, so be careful. Could be fixed by changing the align property of the struct.

What is the meaning of "Yes, Virginia, it had better be unsigned"?

In the linux source code version 3.18 (and previous), in the string.c file, in the function strncasecmp, the very first thing is:
/* Yes, Virginia, it had better be unsigned */
unsigned char c1, c2;
As can be seen here: http://lxr.free-electrons.com/source/lib/string.c
What is the meaning of this?
string.c:strncasecmp() calls __tolower from include/linux/ctype.h which expects an unsinged char.
EDITed to add: In general you always want to pass unsigned char to ctype.h functions because of C Standard ยง7.4, which says the behavior is undefined if the argument to ctype.h functions is not representable as unsigned char or EOF. So that probably explains the "Yes, Virginia" bit.
What is a bit more mysterious is that include/linux/ctype.h actually appears idiot-proof in this respect, because it does its own safety-minded cast in #define __ismask(x) (_ctype[(int)(unsigned char)(x)]). I'm not sure when the "Yes, Virginia" comment was added relative to this other line, but with the current version of include/linux/ctype.h it appears that string.c:strncasecmp() would work fine even with char for c1 and c2. I haven't really tried to change & test it that way though...
Also if you go back to Linux 2.0.40's ctype.h, the safety-minded cast ((int)(unsigned char)) is not there anymore. There's no "Virginia" comment either in 2.0.40's string.c, but there's not even a strncasecmp in it. It looks like both changes were made somewhere in between Linux 2.0 and 2.2, but I can't tell you more right now which came first, etc.

Using the C preprocessor to determine current scope?

I am developing an application in C / Objective-C (No C++ please, I already have a solution there), and I came across an interesting use case.
Because clang does not support nested functions, my original approach will not work:
#define CREATE_STATIC_VAR(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
This code would compile fine with GCC, but because clang doesn't support nested functions, I get a compile error:
Expected ';' at end of declaration.
So, I found a solution that works for Clang on variables inside a function:
#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage
However, I was wondering if there was a way to leverage macro concatenation to choose the appropriate one for the situation, something like:
#define CREATE_STATIC_VAR_GLOBAL(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage
#define SCOPE_CHOOSER LOCAL || GLOBAL
#define CREATE_STATIC_VAR(Type, Name, DFLT) CREATE_STATIC_VAR_ ## SCOPE_CHOOSER(Type, Name, Dflt)
Obviously, the ending implementation doesn't have to be exactly that, but something similar will suffice.
I have attempted to use __builtin_constant_p with __func__, but because __func__ is not a compile-time constant, that wasn't working.
I have also tried to use __builtin_choose_expr, but that doesn't appear to work at the global scope.
Is there something else I am missing in the docs? Seems like this should be something fairly easy to do, and yet, I cannot seem to figure it out.
Note: I am aware that I could simply type CREATE_STATIC_VAR_GLOBAL or CREATE_STATIC_VAR_LOCAL instead of messing with macro concatenation, but this is me attempting to push the limits of the compiler. I am also aware that I could use C++ and get this over with right away, but that's not my goal here.
#define SCOPE_CHOOSER LOCAL || GLOBAL
#define CREATE_STATIC_VAR(Type, Name, DFLT) CREATE_STATIC_VAR_ ## SCOPE_CHOOSER(Type, Name, Dflt)
The biggest difficulty here is that the C preprocessor works by textual substitution, so even if you figured out how to get SCOPE_CHOOSER to do what you want, you'd end up with a macro expansion that looked something like
CREATE_STATIC_VAR_LOCAL || GLOBAL(Type, Name, Dflt);
There's no way to get the preprocessor to "constant-fold" macro expansions during substitution; the only time things are "folded" is when they appear in #if expressions. So your only hope (modulo slight handwaving) is to find a single construction that will work both inside and outside of a function.
Can you explain more about the ultimate goal here? I don't think you can load the variable's initial value with __attribute__((constructor)), but maybe there's a way to load the initial value the first time the function body is entered... or register all the addresses of these variables into a global list at compile-time and have a single __attribute__((constructor)) function that traverses that list... or some mishmash of those approaches. I don't have any specific ideas in mind, but maybe if you give more information something will emerge.
EDIT: I don't think this helps you either, since it's not a preprocessor trick, but here is a constant-expression that will evaluate to 0 at function scope and 1 at global scope.
#define AT_GLOBAL_SCOPE __builtin_types_compatible_p(const char (*)[1], __typeof__(&__func__))
However, notice that I said "evaluate" and not "expand". These constructs are compile-time, not preprocessing-time.
Inspired by the #Qxuuplusone answer.
The suggested macro for AT_GLOBAL_SCOPE does indeed work (in GCC), but causes a compiler warning (and I am pretty sure it cannot be silenced by Diagnostic Pragma because it's created by pedwarn with a test here).
Unless you turn on -w you will always see these warnings and have, in the back of your mind, a horrible feeling that you probably shouldn't be doing whatever it is that you are doing.
Fortunately, there is a solution that can silence these lingering doubts.
In the Other Builtins section, there is __builtin_FUNCTION with this very interesting description (emphasis mine):
This function is the equivalent of the __FUNCTION__ symbol and returns an address constant pointing to the name of the function from which the built-in was invoked, or the empty string if the invocation is not at function scope.
It turns out, at least in version 8.3 of GCC, you can do this:
#define AT_GLOBAL_SCOPE (__builtin_FUNCTION()[0] == '\0')
This still probably won't answer the original question, but until GCC decides this too will cause a warning (it kind of seems like it's intentionally designed not to though), it lets me continue doing questionable things using macros without anything to warn me that it's a bad idea.

Resources