There are 2 different issues in current code regarding maximum filename length:
1- We use FILENAME_MAX which is defined as 4096, while most filesystems have a max length of 256. Replacing FILENAME_MAX with NAME_MAX fixes this first problem (could not test on Windows if it works)
2- We are calculating the maximum length on the UTF-8 string, then encoding to percent encoding. This can result in longer strings since single characters will be replaced by a percent string. So in some situations, we end up with a string longer than allowed. Doing the percent encoding before length calculation fixes the problem.