#' Save a nearest-neighbor index
#'
#' Save an index for nearest-neighbor searching to disk.
#' 
#' @param BNINDEX A \linkS4class{BiocNeighborIndex} object representing a pre-built index, typically from \code{\link{buildIndex}}.
#' @param dir String containing the path to a directory in which to save the index.
#' This directory should already exist.
#' @param ... Further arguments to pass to specific methods.
#' 
#' @return
#' One or more files are created on disk inside \code{dir}.
#' These can be used to reconstitute \code{BNINDEX} by calling \code{\link{loadIndex}}.
#'
#' @details
#' Files generated by \code{saveIndex} are not guaranteed to be portable across architectures, compilers, or even versions of \pkg{BiocNeighbors}.
#' An index saved in this manner is only intended to be read back to the same R environment on the same machine.
#' 
#' @author
#' Aaron Lun
#' 
#' @examples
#' Y <- matrix(rnorm(100000), ncol=20)
#' k.out <- buildIndex(Y)
#'
#' tmp <- tempfile()
#' dir.create(tmp)
#' saveIndex(k.out, tmp)
#' list.files(tmp, recursive=TRUE)
#'
#' @name saveIndex
NULL

#' @export
#' @rdname saveIndex 
setMethod("saveIndex", "BiocNeighborGenericIndex", function(BNINDEX, dir, ...) {
    generic_save_index(BNINDEX@ptr, dir)

    if (!is.null(BNINDEX@names)) {
        names.path <- paste0(dir, "r_names")
        write(file=names.path, BNINDEX@names)
    }

    invisible(NULL)
})
