#' Load the instance back from \code{\link{xgb.serialize}}
#'
#' @param buffer the buffer containing booster instance saved by \code{\link{xgb.serialize}}
#'
#' @export
xgb.unserialize <- function(buffer) {
  cachelist <- list()
  handle <- .Call(XGBoosterCreate_R, cachelist)
  tryCatch(
    .Call(XGBoosterUnserializeFromBuffer_R, handle, buffer),
    error = function(e) {
      error_msg <- conditionMessage(e)
      m <- regexec("(src[\\\\/]learner.cc:[0-9]+): Check failed: (header == serialisation_header_)",
                   error_msg, perl = TRUE)
      groups <- regmatches(error_msg, m)[[1]]
      if (length(groups) == 3) {
        warning(paste("The model had been generated by XGBoost version 1.0.0 or earlier and was ",
                      "loaded from a RDS file. We strongly ADVISE AGAINST using saveRDS() ",
                      "function, to ensure that your model can be read in current and upcoming ",
                      "XGBoost releases. Please use xgb.save() instead to preserve models for the ",
                      "long term. For more details and explanation, see ",
                      "https://xgboost.readthedocs.io/en/latest/tutorials/saving_model.html",
                      sep = ""))
        .Call(XGBoosterLoadModelFromRaw_R, handle, buffer)
      } else {
        stop(e)
      }
    })
  class(handle) <- "xgb.Booster.handle"
  return (handle)
}
