Skip to content

Lapis-chan v1.2.5 - Random Numbers!

Latest
Compare
Choose a tag to compare
@karai17 karai17 released this 30 Nov 00:43
· 32 commits to master since this release

So to start off on this, I need to talk about math.random. math.random is great when you want a random number. Problem is, it was giving me too many collisions. Let me explain. The way that random seeding works is that you provide Lua with a seed, and using that seed it generates a sequence of random numbers. The problem? I need to reset the seed for each request. Now, why is this a problem? Because I use os.time as my seed. This means that for an entire second, anyone who uploads an image is going to get the exact same timestamp for a file name AND the exact same random number generated from the exact same seed. The whole point of the random number is to stop file name collision, and this would be effectively useless in doing so. Imagine if 4chan's /b/ had a whole second where everyone posting would overwrite files. You would get a lot of collisions.

For my first attempt at solving this, I did an extremely hacky thing. I am not proud of it, but it worked. What I did was I found something that was guaranteed to be unique. In this case, I used the memory address of whatever table I had handy. When I would tostring that table, I'd get something like table: 0xab56d39. Well, that's a hexadecimal number with some text prepended to it. So what I did was strip table: and run the remaining text through tonumber to get a decimal number. With that, I'd carve off the last 3 digits and voila! A random number that doesn't collide nearly as often.

But that's insane. This patch changes how all that nonsense works. Now we simply pull 4 bytes out of /dev/urandom, convert them to a uint32_t using LuaJIT's FFI, then snag the last 3 digits from that. Much cleaner, much saner, much better.