The 11 lines of code above do everything you’re asking, and they do it efficiently — I think you’re overestimating the amount of low-level magic required to do this. 
The 11 lines of code above do everything you’re asking, and they do it efficiently — I think you’re overestimating the amount of low-level magic required to do this. 