1

I am wondering what would be the equivalent to nodeJS charCodeAt in Rust? I have tried digging into the Rust documentation but I have not gotten very far.

However here is where I got so far - it might be not as useful, I do appreciate directions.

Rust

fn main() {
    let v1 = "\0\u{1e}2022-Dec-2 11:42:16-0800\0";

    println!("{:?}", v1.chars().nth(01));
}

let ReadShort = function (v, p) {
    return (v.charCodeAt(p) << 8) + v.charCodeAt(p + 1);
};

let v1 = "\0\u{1e}2022-Dec-2 11:42:16-0800\0";

console.log(ReadShort(v1, 0) == 30); // expected result true
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
7skies
  • 167
  • 4
  • 17
  • Can you explain for those who don't know Node what you expect the Rust code to do? – mkrieger1 Dec 14 '22 at 13:55
  • The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. I was expecting to get the integer value, i was able to select the portion charachters that has the wanted value, but did not know how tp parse it. – 7skies Dec 14 '22 at 14:02
  • If you are willing to accept the UTF-8 code unit at the nth pos, maybe because your string is mostly ASCII you can do `v1.as_bytes()[n]`. – rodrigo Dec 14 '22 at 14:20
  • 1
    Does this answer your question? [How can I convert a buffer of a slice of bytes (&\[u8\]) to an integer?](https://stackoverflow.com/questions/29307474/how-can-i-convert-a-buffer-of-a-slice-of-bytes-u8-to-an-integer) – justinas Dec 14 '22 at 14:20
  • 1
    It looks like you're parsing a binary format, and you want to parse the first two bytes as a big-endian 16-bit integer. In that case, I would suggest against treating this binary message as a string. Please see whether my suggested question helps. – justinas Dec 14 '22 at 14:22
  • @justinas Can not change the current structure of the code. The binary will be part of the string at different indexes. The accepted answer here solves the problem. – 7skies Dec 14 '22 at 14:30

1 Answers1

1

The "character code" is just the underlying bytes of the character, also known as the Unicode code point. You can get it by a simple conversion to an integer:

fn main() {
    let v1 = "\0\u{1e}2022-Dec-2 11:42:16-0800\0";
    let character = v1.chars().nth(1).unwrap();
    let code = u32::from(character);
    println!("{}", code);
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • Thank you, the parsing part is what i was missing. I guise there is no need to implement the `ReadShort` function, using rust-lang `left-shift`, right? – 7skies Dec 14 '22 at 14:06
  • @7skies I'm afraid I don't know what you are referring to there. – Peter Hall Dec 14 '22 at 14:08