Skip to content

Commit

Permalink
feat: invalid input handling
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrolcn committed Apr 22, 2020
1 parent 8898856 commit c38fd2d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cpf-wasm"
version = "0.1.0"
version = "0.1.1"
authors = ["Pedro Nascimento <[email protected]>"]
edition = "2018"

Expand All @@ -26,6 +26,9 @@ console_error_panic_hook = { version = "0.1.1", optional = true }
# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now.
wee_alloc = { version = "0.4.2", optional = true }

# JS object bindings
js-sys = "0.3.37"

[dev-dependencies]
wasm-bindgen-test = "0.2"

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# CPF-WASM

A CPF validation lib using web-assembly
Probably the fastest node cpf validation lib out there.
Written in rust, compiled to WASM

## Installation
Install using the package manager of your choice, it already ships with typings
Expand Down
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod utils;

use wasm_bindgen::prelude::*;
use js_sys::Error;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
Expand Down Expand Up @@ -49,6 +50,14 @@ impl CPF {

#[wasm_bindgen]
pub fn isValid(cpf: String) -> Result<bool, JsValue> {
if cpf.len() != 11 {
return Err(Error::new("cpf must contain exactly 11 characters").into());
}

if !cpf.chars().all(|ch| ch.is_numeric()) {
return Err(Error::new("cpf must contain only numeric characters").into());
}

if CPF_BLACKLIST.iter().any(|bad_cpf| bad_cpf == &cpf.as_str()) {
return Ok(false)
}
Expand Down Expand Up @@ -84,4 +93,20 @@ mod test {
false
)
}

#[test]
fn too_short() {
assert_eq!(
isValid("1234567890".to_owned()),
Err(Error::new("cpf must contain exactly 11 characters").into())
)
}

#[test]
fn invalid_input() {
assert_eq!(
isValid("1234567890a".to_owned()),
Err(Error::new("cpf must contain only numeric characters").into())
)
}
}

0 comments on commit c38fd2d

Please sign in to comment.