emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Preferring ptrdiff_t to ssize_t


From: Paul Eggert
Subject: Preferring ptrdiff_t to ssize_t
Date: Wed, 01 Oct 2014 13:29:40 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.1.1

The Emacs C code prefers signed integer types to unsigned, so it typically uses ptrdiff_t for indexes that might not fit in 'int'. At first glance, another type ssize_t is a plausible alternative, as the two types are equivalent on typical platforms. On less-common platforms, though, ptrdiff_t works better than ssize_t, so for size-related integers Emacs's portable C code should continue to prefer ptrdiff_t.

Here are some details about this:

1. Historically, some 64-bit Unix-based platforms had 32-bit ssize_t even though size_t and ptrdiff_t were both 64-bit, because they had 32-bit 'int' and wanted system calls like 'read' to support the traditional default API where 'read' returned 'int'. I don't know whether these platforms have died out entirely, but I suspect they haven't.

2. A few platforms even now have ptrdiff_t wider than size_t, thus avoiding the problem of integer overflow when subtracting pointers. Using ptrdiff_t could therefore improve the quality of Emacs ports to these platforms, even if Emacs doesn't happen to run there now.

3. ptrdiff_t is more ubiquitous and better-standardized than ssize_t, as ptrdiff_t is required by the C standard whereas ssize_t is required only by POSIX.

4. There are standard printf formats for prtdiff_t (e.g, "%td") but not for ssize_t.

5. To avoid problems with integer overflows in ptrdiff_t-related calculations, Emacs never allocates objects larger than PTRDIFF_MAX bytes. On platforms where PTRDIFF_MAX != SSIZE_MAX this approach wouldn't work if ssize_t started to be used extensively.

6. POSIX requires only that ssize_t be able to store values in the range [-1, SSIZE_MAX], which makes it an iffy choice (at least in theory) for containing negative values other than -1.

I'm bringing this up now because in emacs-24 bzr 117515 Eli introduced a ssize_t local variable, in trunk bzr 117993 I changed it to ptrdiff_t, and Eli reverted the latter change in trunk bzr 117997. In this particular case the value happens to be an 'int', so on second thought perhaps Emacs should just declare it as 'int' rather than mess with *_t types. More generally, though, when size-related values might not fit in 'int', Emacs should continue to prefer ptrdiff_t to ssize_t in portable code. I plan to add a paragraph to internals.texi to help document this.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]