Hacker News new | past | comments | ask | show | jobs | submit login

They are longer to type than `+`.

It is easy to write unsafe code and difficult to write safe code. As a result, while most mathematical operations must be safe, developers use unsafe operations because they are easier to type and more readable.

Operators like `+` should be equivalent to checked_add().unwrap(), not to unchecked_add(). Why choose unsafe and rarely used operation as a default? It is a mistake. Swift uses sane defaults.

UPD: for example, let's say we need to allocate memory for N elements of size S and a header of size H. Here is the unsafe code:

    u32 s = N * S + H
And here is safe code:

    u32 s = checked_add(checked_mul(N, S).unwrap(), H).unwrap()
And here is safe code in Swift:

    let s: Uint32 = N * S + H
And unsafe code in Swift:

    let s = N &* S &+ H



In the "unsafe" example in Swift can you get to undefined behavior?

In your "unsafe" example in Rust, you still don't get undefined behavior.

https://huonw.github.io/blog/2016/04/myths-and-legends-about...


> In your "unsafe" example in Rust, you still don't get undefined behavior.

You get an unexpected behaviour instead. For example, imagine if you had a device for counting amount of bytes transferred over the network. If the counter overflows, you will get the wrong number, and issue an invalid bill to the customer. While that is a "defined" behaviour that is not what one expects.

I expect the counter either to work correctly according to normal math rules or indicate that it cannot perform the task due to hardware limitations.

One might blame the developer but history shows that developers fail to take account of overflow. For example, experienced developers writing Linux kernel made several mistakes, which lead to security vulnerabilities.

In most cases developers need standard math, not operations modulo 2^32 or 2^64. When you count bytes, you need an exact amount, not an amount modulo 2^32. Why do language designers provide modulo operations instead of normal math I don't understand.

Rust has chosen a weird path when the program works differently in debug and release mode. This is clearly wrong. I expect the same program to work the same way no matter whether optimizations are enabled or not.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: