Leftpad-rs
github.com
github.com
(You can use that code freely and without any attribution if you want to.)
The important part here is to use `String::with_capacity()` to prevent unnecessary reallocations. Furthermore I used `usize::saturating_sub()` because it's neat and cleaned up the code with `rustfmt` (which you should use).
https://github.com/hfiguiere/leftpad-rs/pull/2
Sadly it has gathered some rust (pun intended !)
[edit] thanks for the explanation, I'm not familiar with rust and just assumed the bang would mean !=
In rust macro functions look like functions but end in a bang(!), it's not using ! to mean negate. http://rustbyexample.com/macros.html
Usage example: https://doc.rust-lang.org/std/macro.assert_eq!.html
The optimal solution would be instead if you create a `CollectionType` which repeats the padding character N times. That way you could use `insertContentsOf(_:at:)` to insert N characters at once into the string and move the contents of the string only once.
If that doesn't work for you might as well simply allocate a new `String`, reserve `pad` chars of space, insert the `pad` chars and then insert the previous string. Even that is probably still faster than your previous approach.
In the end it's still probably the easiest approach in practice to simply use the `NSString` method `stringByPaddingToLength(_:withString:startingAtIndex:)`... :D
While my implementation is basically a direct port of node's leftpad, pull requests are welcome. :)
https://gist.github.com/zelcon5/7dc42bf91ea958132a0d
- "padding" can go either left or right.
- generic function
- minimal lines of code
Wow so great, make me a dependency for Windows11, Apache, Firefox, and toasters.
(and no I didn't post that to HN either)