I had to do this recently but kept things basic and tailored to the usecase at hand relying on some assumptions.
With help I figured the solution at https://codeberg.org/mro/seppo/src/commit/841f6dbcaf737b1343804180d07e0f6ea9efa47d/lib/as2.ml#L484 and personally find it too trivial for a library and am opinionated about design decisions. But tastes differ – some even find a leftpad package a good idea.