| 1 |
#' Try to use the system native encoding to represent a character vector |
| 2 |
#' |
| 3 |
#' Apply `enc2native()` to the character vector, and check if `enc2utf8()` can |
| 4 |
#' convert it back without a loss. If it does, return `enc2native(x)`, otherwise |
| 5 |
#' return the original vector with a warning. |
| 6 |
#' @param x A character vector. |
| 7 |
#' @note On platforms that supports UTF-8 as the native encoding |
| 8 |
#' ([l10n_info()]`[['UTF-8']]` returns `TRUE`), the conversion will be |
| 9 |
#' skipped. |
| 10 |
#' @export |
| 11 |
#' @examples |
| 12 |
#' library(xfun) |
| 13 |
#' s = intToUtf8(c(20320, 22909)) |
| 14 |
#' Encoding(s) |
| 15 |
#' |
| 16 |
#' s2 = native_encode(s) |
| 17 |
#' Encoding(s2) |
| 18 |
native_encode = function(x) { |
| 19 |
if (isTRUE(l10n_info()[['UTF-8']])) return(x) |
| 20 |
if (identical(enc2utf8(x2 <- enc2native(x)), x)) return(x2) |
| 21 |
warning('The character vector cannot be represented in the native encoding') |
| 22 |
x |
| 23 |
} |
| 24 |
|
| 25 |
#' Check if a character vector consists of entirely ASCII characters |
| 26 |
#' |
| 27 |
#' Converts the encoding of a character vector to `'ascii'`, and check if |
| 28 |
#' the result is `NA`. |
| 29 |
#' @param x A character vector. |
| 30 |
#' @return A logical vector indicating whether each element of the character |
| 31 |
#' vector is ASCII. |
| 32 |
#' @export |
| 33 |
#' @examples library(xfun) |
| 34 |
#' is_ascii(letters) # yes |
| 35 |
#' is_ascii(intToUtf8(8212)) # no |
| 36 |
is_ascii = function(x) { |
| 37 |
out = iconv(x, to = 'ascii') == x |
| 38 |
out[is.na(out)] = FALSE |
| 39 |
out[is.na(x)] = NA |
| 40 |
out |
| 41 |
} |