# add one

### o2sh ・1 min read

Here is a little program I wrote in Rust that allows you to add one to any number

# add-one

Returns n + 1.

## Usage

Add this to your `Cargo.toml`

:

```
[dependencies]
add-one = "1.0.0"
```

and this to your crate root:

`extern crate add_one;`

## Example

```
extern crate add_one;
use add_one::add_one;
use std::str;
fn main() {
let mut bytes = Vec::new();
match add_one("123".as_bytes(), &mut bytes) {
Ok(()) => println!("{}", str::from_utf8(&bytes).unwrap()),
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
```

or

```
$ cargo run 12
$ 13
```

## Thanks

## License

Licensed under

- MIT license (LICENSE.md or http://opensource.org/licenses/MIT)

## Compatibility

The `add-one`

crate is tested for rustc 1.26 and greater.

The idea is pretty simple. Indeed, since incrementing a number leaves most of it unchanged, it's much faster to work on the decimal digits itself.

As a consequence, after breaking the input into a list of digits, we just have to increment or decrement (in case of negative input) the last number.

####
*Not so fast...*

What if the number has trailing nines for positive inputs or trailing zeros for negative numbers ?

Well, if the number has trailing nines (e.g.: 7561325999) or trailing zeros (e.g.: -1645000), we just need to increment the last "non-nine" digit (or decrement the last "non-zero" digit) and switch the nines into zeros and zeros into nines (for negative inputs).

And, in the case of floating point inputs (e.g.: 15691.12313) we simply ignore the decimal part and apply the previous rule to the integer part.

####
*Unless...*

...the input belongs to ]-1,0[ (e.g.: -0.2 + 1 = 0,8 (not 1.2!)). In which case, we have to give it a special treatment.

Thanks for reading ! :)

Why is such a thing needed? Can't Rust do that yet?

(I would like to point out that this sounds a lot like Node-ism: npm has multiple (!) packages for "noop"...)

It's a different approach without the limitations. Indeed, the input is not bound to a type (i32, i64...) and can be very big.

It may also be faster...

Right so your entire function would run faster than what effectively compiles to a single CPU instruction... 🤔

github.com/sindresorhus/ama/issues...