I've just completed a CodeWars kata on vowel-counting in C & Rust. The sample code is easy & obvious. Arrays can be used as fast mappings. Here, I map characters to logical values (0 or 1).
C implementation:
#include <stddef.h>
#include <stdint.h>
// :) This const array design looks smart & IMO-readable. Use of C99 feature.
const uint8_t areVowels[256]= {['a']=1, ['e']=1, ['i']=1, ['o']=1, ['u']=1};
size_t get_count(const unsigned char *s)
{
auto size_t count= 0;
for (;*s!='\0';s++){
count+= areVowels[*s];
}
return count;
}
Rust implementation:
// :( Here is me pain. Unreadable, python3-generated array content.
const ARE_VOWELS:[u8;256]= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
fn get_count(s: &str) -> usize {
let mut vowels_count: usize = 0;
for c in s.bytes(){
vowels_count+= ARE_VOWELS[c as usize] as usize;
}
return vowels_count;
}
I wish I knew an alternative for array designators in Rust, which are a useful C99 feature. Initialization of the same byte array is much more awkward in my Rust code.