Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Swift's malloc/MemoryLayout.size take/return signed integers?

public func malloc(_ __size: Int) -> UnsafeMutableRawPointer!

@frozen public enum MemoryLayout<T> {
    public static func size(ofValue value: T) -> Int
    ...

When in C malloc/sizeof take/return size_t which is unsigned?
Isn’t Swift calling libc under the hood?

EDIT: is this the reason why? https://qr.ae/pvFOQ6
They are basically trying to get away from C’s legacy?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, it’s calling the libc functions under the hood.

The StdlibRationales.rst document in the Swift repo explains why it imports size_t as Int:

Converging APIs to use Int as the default integer type allows users to write fewer explicit type conversions.

Importing size_t as a signed Int type would not be a problem for 64-bit platforms. The only concern is about 32-bit platforms, and only about operating on array-like data structures that span more than half of the address space. Even today, in 2015, there are enough 32-bit platforms that are still interesting, and x32 ABIs for 64-bit CPUs are also important. We agree that 32-bit platforms are important, but the usecase for an unsigned size_t on 32-bit platforms is pretty marginal, and for code that nevertheless needs to do that there is always the option of doing a bitcast to UInt or using C.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading