I did come up with an implementation that works, and it seems sound based on some code that I threw at it, but I am not 100% sure about it. Also I resorted to a slightly nasty trick in order to return a reference with the same lifetime as the input, and maybe there is a better way to do it.
Would anyone please review and perhaps suggest any improvements?