R/staticimports.R

Defines functions str_pad str_extract

# Generated by staticimports; do not edit by hand.
# ======================================================================
# Imported from pkg:stringstatic
# ======================================================================

str_extract <- function(string, pattern) {
  if (length(string) == 0 || length(pattern) == 0) {
    return(character(0))
  }

  is_fixed <- inherits(pattern, "stringr_fixed")

  result <- Map(
    function(string, pattern) {
      if (is.na(string) || is.na(pattern)) {
        return(NA_character_)
      }

      regmatches(
        x = string,
        m = regexpr(
          pattern = pattern, text = string, perl = !is_fixed, fixed = is_fixed
        )
      )
    },
    string, pattern,
    USE.NAMES = FALSE
  )

  result[lengths(result) == 0] <- NA_character_
  unlist(result)
}

str_pad <- function(string, width, side = c("left", "right", "both"), pad = " ", use_width = TRUE) {
  if (!is.numeric(width)) {
    return(string[NA])
  }

  if (any(nchar(pad, type = "width") != 1)) {
    stop("each string in `pad` should consist of code points of total width 1")
  }

  side <- match.arg(side)

  nchar_type <- if (isTRUE(use_width)) "width" else "chars"
  string_width <- nchar(string, nchar_type)
  pad_width <- width - string_width
  pad_width[pad_width < 0] <- 0

  switch(side,
    "left" = paste0(strrep(pad, pad_width), string),
    "right" = paste0(string, strrep(pad, pad_width)),
    "both" = paste0(
      strrep(pad, floor(pad_width / 2)),
      string,
      strrep(pad, ceiling(pad_width / 2))
    )
  )
}
elipousson/bcps documentation built on Feb. 7, 2024, 2:58 a.m.