thanks for all the effort... looks good to me
one last nitpick: it really looks like NULL mask or mask with 0 length are treated the same way, so this could be factorized further like in the attached patch so that one no longer needs to take care of 0 length masks
[patch](/uploads/9b6e11a7cc177841db096c6320b1f10a/patch)