Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

Does idiomatic rust code always avoid 'unsafe'?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should avoid unsafe unless there are 2 situations:

  1. You are doing something which impossible to do in safe code e.g. FFI-calls. It is a main reason why unsafe ever exists.
  2. You proved using benchmarks that unsafe provide big speed-up and this code is bottleneck.

Your arguing

I know I could easily do a checked cast and unwrap it, but that feels a bit silly because of how certain I am that the check can never fail.

is valid about current version of your code but you would need to keep this unsafe in mind during all further development.

Unsafe greatly increase cognitive complexity of code. You cannot change any place in your function without keeping unsafe in mind, for example.

I doubt that utf8 validation adds more overhead than possible reallocation in result.insert(0, _1); in your code.

Other nitpicks:

  1. You should add a comment in unsafe section which explains why it is safe. It would make easier to read a code for a other people (or other you after a year of don't touching it).
  2. You could define your constants as const _0: u8 = b'0';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...