It's implemented in revwalk.c so it has access to the revision walker's commit cache and related functions. The algorithm is the one used by git, modified so it fits better with the library's functions.