Safe casting functions

I'm referring to the change in 9d135f7, and the assertions on lines 38-39.