@@ -7,6 +7,7 @@ check_object <- function(x,
77 check_fun ,
88 what ,
99 ... ,
10+ allow_na = FALSE ,
1011 allow_null = FALSE ,
1112 arg = caller_arg(x ),
1213 call = caller_env()) {
@@ -18,6 +19,9 @@ check_object <- function(x,
1819 if (allow_null && is_null(x )) {
1920 return (invisible (NULL ))
2021 }
22+ if (allow_na && all(is.na(x ))) {
23+ return (invisible (NULL ))
24+ }
2125 }
2226
2327 stop_input_type(
@@ -69,6 +73,60 @@ check_inherits <- function(x,
6973 )
7074}
7175
76+ check_length <- function (x , length = integer(), ... , min = 0 , max = Inf ,
77+ arg = caller_arg(x ), call = caller_env()) {
78+ if (missing(x )) {
79+ stop_input_type(x , " a vector" , arg = arg , call = call )
80+ }
81+
82+ n <- length(x )
83+ if (n %in% length ) {
84+ return (invisible (NULL ))
85+ }
86+ fmt <- if (inherits(arg , " AsIs" )) identity else function (x ) sprintf(" `%s`" , x )
87+ if (length(length ) > 0 ) {
88+ type <- paste0(" a vector of length " , oxford_comma(length ))
89+ if (length(length ) == 1 ) {
90+ type <- switch (
91+ sprintf(" %d" , length ),
92+ " 0" = " an empty vector" ,
93+ " 1" = " a scalar of length 1" ,
94+ type
95+ )
96+ }
97+ msg <- sprintf(
98+ " %s must be %s, not length %d." ,
99+ fmt(arg ), type , n
100+ )
101+ cli :: cli_abort(msg , call = call , arg = arg )
102+ }
103+
104+ range <- pmax(range(min , max , na.rm = TRUE ), 0 )
105+ if (n > = min & n < = max ) {
106+ return (invisible (NULL ))
107+ }
108+ if (identical(range [1 ], range [2 ])) {
109+ check_length(x , range [1 ], arg = arg , call = call )
110+ return (invisible (NULL ))
111+ }
112+
113+ type <- if (range [2 ] == 1 ) " scalar" else " vector"
114+
115+ what <- paste0(" a length between " , range [1 ], " and " , range [2 ])
116+ if (identical(range [2 ], Inf )) {
117+ what <- paste0(" at least length " , range [1 ])
118+ }
119+ if (identical(range [1 ], 0 )) {
120+ what <- paste0(" at most length " , range [2 ])
121+ }
122+
123+ msg <- sprintf(
124+ " `%s` must be a %s with %s, not length %d." ,
125+ fmt(arg ), type , what , n
126+ )
127+ cli :: cli_abort(msg , call = call , arg = arg )
128+ }
129+
72130# ' Check graphics device capabilities
73131# '
74132# ' This function makes an attempt to estimate whether the graphics device is
0 commit comments