Refactor the implementation to avoid duplication; use the result of the API to determine the proper buffer size to use.