Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

RFC: rename int and uint to intptr/uintptr #9940

Closed

Description

@thestinger

An arbitrarily sized integer type would be provided in std under the name Int. I think encouraging use of an arbitrarily sized integer when bounds are unknown is a much better solution than adding failure throwing overflow checks to fixed-size integers.

Activity

  1. emberian commented on Oct 19, 2013

    @emberian
    Contributor

    I think intptr and uintptr are awful names, but the best alternatives I can come up with is word and sword, which are worse.

    Fixed integers of pseudo-arbitrary width are rarely useful.

  2. Thiez commented on Oct 19, 2013

    @Thiez
    Contributor

    Seems to me int and uint are not pointers, so a 'ptr' suffix doesn't make a whole lot of sense. What would the type be of the ~[T].len() and [T, ..n].len()? Surely not uintptr. Perhaps introduce size_t?

    I rather like the int and uint types. Why can't they coexist with Int? If they're going to get renamed to something ugly perhaps it would be best to stick with intptr_t and uintptr_t, existing Rust users are going to have to get used to the new stuff anyway, and it'll be easier to remember for those coming from C/C++.

    I think the machine-word-sized int and uint are really nice to use as they are at this time. Int could be BigInt or Integer for people who really want arbitrary sized integers, but I'm thinking the vast majority of the time you don't want/need that functionality anyway.

  3. huonw commented on Oct 19, 2013

    @huonw
    Contributor

    intptr_t and uintptr_t

    Why introduce a completely new & (so far) unused naming convention to the language?

  4. thestinger commented on Oct 19, 2013

    @thestinger
    ContributorAuthor

    @Thiez: They aren't machine word size, they're pointer-size. On the x32 ABI they will be 32-bit, despite having 16 64-bit integer registers. If you want to use fixed-size integers correctly, you need upper bounds on the size. Fixed-size types named int/uint encourage writing buggy code because it implies they are a sane default rather than just a way to deal with sizes smaller than the address space.

  5. Thiez commented on Oct 19, 2013

    @Thiez
    Contributor

    @thestinger fair point. Perhaps that should change as well? Since we're not really supposed to be messing around with pointers outside of unsafe blocks, perhaps a pointer-size type is deserving of an ugly name. That opens up the option of having int and uint be machine word sized...

  6. thestinger commented on Oct 19, 2013

    @thestinger
    ContributorAuthor

    @cmr: I agree they're awful names. We should discourage using fixed-size types only when bounds are unknown. I think you only want these types in low-level code or for in-memory container sizes.

    @Thiez: I don't really think word-sized is a useful property. If the upper bound is 32-bit, 32-bit integers will likely be fastest for the use case due to wasting less cache space.

  7. Thiez commented on Oct 19, 2013

    @Thiez
    Contributor

    I realize my suggestion is silly anyway as one would still need a pointer-size variable for array and vector lengths, which is a nice case for int/uint (but not when they're word-sized). Ignore it :)

  8. 1fish2 commented on Oct 19, 2013

    @1fish2

    I completely agree with @thestinger

    A machine-word sized integer means bugs and security holes e.g. because you ran the tests on one platform then deployed on others.

    If one of the platforms has 16-bit int like PalmOS, that's too short to use without thinking carefully about it, so the prudent coding style forbids un-sized int and uint. (Actually the PalmOS 68000 ABI is emulated on a 32-bit ARM so it's not clear what's a machine word.)

    Hence the strategy of using a pointer-size integer type only in low-level code that requires it, with an ugly name.

  9. UtherII commented on Oct 19, 2013

    @UtherII

    I agree that using int and uint should be discouraged and renaming them to a less straightforward name is better.
    I don't know how type inference works but I think it should avoid using them by default too.

  10. michaelwoerister commented on Oct 19, 2013

    @michaelwoerister
    Contributor

    I think that's a good idea. You can't really rely on very much when using int/uint.

    I'm not so fond of the names intptr/uintptr. Given that the use cases for these types would be rare, I think they could also be defined in the standard library with more verbose names like PointerSizedInt / PointerSizedUInt. Not much ambiguity there. One could also define other integer types in the same module in the vain of C's uint_fast8_t and uint_least8_t in stdint.h to tackle the "machine word" problem.

  11. glaebhoerl commented on Oct 19, 2013

    @glaebhoerl
    Contributor

    IMHO, the interesting questions are: what type should be used to index into arrays, and what should it be named? Indexing into arrays is pretty common. A pointer-sized type is needed to be able to represent any index. It should presumably be unsigned. I'm not sure if there's much reason to also have a signed version. Expanding to a BigInt on overflow doesn't make much sense here. But wrapping around on over/underflow also doesn't make very much sense, I think. If you want to catch over/underflow and fail!() or similar, you lose a lot (or all) of the performance advantage you might have had over the expand-to-BigInt version. So there's decent arguments in favor of expanding, wrapping, as well as trapping.

    I think the strongest argument might be for expanding: negative or larger-than-the-address-space values don't make sense for array indexes, but the array bounds check will already catch that. Meanwhile it's versatile and generally useful for most other situations as well, not just array indexing. The downside is a performance cost relative to a type that wraps on over/underflow. (In the event of a fixed pointer-sized type, the relevant association when naming it should be that it holds any array index, not that it's pointer-sized.)

    Whatever this type ends up being and named, it's the one that should be in the prelude.

    If someone explicitly needs pointer-sized machine integers for unsafe hackery, those could indeed be named intptr and uintptr and buried in a submodule somewhere.

  12. bstrie commented on Oct 19, 2013

    @bstrie
    Contributor

    Dumb question here, but what's the use of having a signed pointer-sized int at all? Could we get away with having only uintptr (or whatever it ends up being called)?

    As for the general idea of this bug, I'm warming to it after seeing how well the removal of float has worked. Having to actually think about the size of my types has been quite illuminating.

  13. thestinger commented on Oct 19, 2013

    @thestinger
    ContributorAuthor

    @bstrie: a signed one is needed for offsets/differences (POSIX has ssize_t mostly because they like returning -1 as an error code though! ISO C has ptrdiff_t though)

  14. 1fish2 commented on Oct 19, 2013

    @1fish2

    @thestinger good point. Subtracting array indexes should yield a signed value.

    So to reverse the question, what's the need for an unsigned array index type? Is it feasible to allocate a byte array that takes more than half the address space?

  15. thestinger commented on Oct 19, 2013

    @thestinger
    ContributorAuthor

    AFAIK the rationale for unsigned types here is to avoid the need for a dynamic check for a negative integer in every function. A bounds check only has to compare against the length, and a reserve/with_capacity function only has to check for overflow, not underflow. It just bubbles up the responsibility for handling underflow as far as possible into the caller (if it needs to check at all - it may not every subtract from an index).

  16. 43 remaining items

  17. thestinger commented on Jan 12, 2014

    @thestinger
    ContributorAuthor

    Simple example:

    extern mod extra;
    use std::unstable::intrinsics::{abort, u32_mul_with_overflow};
    use extra::test::BenchHarness;
    
    #[inline(never)]
    fn control(xs: &mut [u32]) {
        for x in xs.mut_iter() {
            *x *= 5;
        }
    }
    
    #[inline(never)]
    fn check(xs: &mut [u32]) {
        for x in xs.mut_iter() {
            unsafe {
                let (y, o) = u32_mul_with_overflow(*x, 5);
                if o {
                    abort()
                }
                *x = y;
            }
        }
    }
    
    #[inline(never)]
    fn check_libstd(xs: &mut [u32]) {
        for x in xs.mut_iter() {
            *x = x.checked_mul(&5).unwrap();
        }
    }
    
    #[bench]
    fn bench_control(b: &mut BenchHarness) {
        b.iter(|| {
            let mut xs = [0, ..1000];
            control(xs)
        });
    }
    
    #[bench]
    fn bench_check(b: &mut BenchHarness) {
        b.iter(|| {
            let mut xs = [0, ..1000];
            check(xs)
        });
    }
    
    #[bench]
    fn bench_check_libstd(b: &mut BenchHarness) {
        b.iter(|| {
            let mut xs = [0, ..1000];
            check_libstd(xs)
        });
    }

    --opt-level=2

    test bench_check        ... bench:      1085 ns/iter (+/- 28)
    test bench_check_libstd ... bench:      1082 ns/iter (+/- 38)
    test bench_control      ... bench:       349 ns/iter (+/- 12)
    

    --opt-level=3

    test bench_check        ... bench:      1080 ns/iter (+/- 14)
    test bench_check_libstd ... bench:      1177 ns/iter (+/- 16)
    test bench_control      ... bench:       350 ns/iter (+/- 11)
    

    Ouch. It becomes a larger slowdown multiplier when you add more operations to the loop too. Since it's increasing the code size a lot, it will bloat the instruction cache too.

  18. CloudiDust commented on Jan 13, 2014

    @CloudiDust

    @thestinger Thanks for the link. I am aware that the names come from the C/C++ standards, but still find them confusing (to rust newcomers from outside the C/C++ world).

    Now come to think of it, this is a convention that can be learnt quickly, and C# actually uses IntPtr in a similar manner, so in this regard, it is quite okay.

    But there may be another problem: the names intptr/uintptr (or intps/uintps for that matter) don't seem to reflect their main use case in safe-mode rust. They should be more akin to ssize_t/size_t than intptr_t/uintptr_t, and there are good reasons why C/C++ differentiates the two pairs. So I think we should differntiate them too.

    This is to say, we may have dedicated names for container-indexing integer types, while the fact that they are pointer sized is an implementation detail on certain architectures, just like in C/C++.

    Here are three pairs of possible candidates: intsize/uintsize, isize/usize and size/ssize. They all have:

    Common pros:

    1. clearer intention than intptr/uintptr.
      (For a C/C++ programmer that is. He/she will accept quickly that a "size" type has something to do with "indexes".)
    2. won't break where size_t and uintptr_t are different.
      (Does rust target such architectures? If not, is it possible that they will be targeted later?)

    Common cons:

    1. not suited for other possible use cases of pointer sized integers.
      (Eh, what are those in safe-mode rust? And in unsafe mode, can we get away with std::libc types?)

    Pros and cons specific to each candidate:

    intsize/uintsize, like intptr/uintptr, are long and out of place, so as to discourage their usage. But I think such "ugliness" is unnecessary, because:

    isize/usize are more in alignment with the rust naming convention, and shorter. They are still somewhat ugly and foreign at first glance, while being specific enough so people won't toss them everywhere.

    On the other hand, ssize/size align with C/C++ ssize_t/size_t. Some may consider this an advantage, but for the most part, safe-mode rust doesn't directly use C/C++ type names anyway. And size does occupy the common word "size".

    So I lean towards isize/usize.

    Regarding an arbitrarily sized Int, in a systems language, people may expect Int to be fix-sized, so I believe BigInt is a better name, signifying the higher cost of such a type.

    I am not sure about my stance on the "default integer type" issue, but people must make informed choices consciously. Some "rusty guidelines to integer type selection" in the docs would be great.

  19. nikomatsakis commented on Jan 13, 2014

    @nikomatsakis
    Contributor

    On Sun, Jan 12, 2014 at 12:55:36PM -0800, Daniel Micay wrote:

    This is well-explored territory with -ftrapv in C. I expect it
    would push Rust significantly behind Java in out-of-the-box
    performance. It's easy enough to directly use the LLVM intrinsics I
    added for this and branch to abort to compare. I can make
    benchmarks and present Rust-specific numbers if that's desired. I
    can also include benchmarks of a number type overflowing to a big
    integer.

    I do not understand how checking for overflow and failing can possibly
    be slower than checking for overflow and promoting to a big
    integer. Perhaps you can elaborate. And yes, benchmarks are precisely
    what I was asking for.

  20. thestinger commented on Jan 13, 2014

    @thestinger
    ContributorAuthor

    I do not understand how checking for overflow and failing can possibly be slower than checking for overflow and promoting to a big integer. Perhaps you can elaborate. And yes, benchmarks are precisely what I was asking for.

    I'm not saying performing a branch on the contained value and then a check for overflow is faster than the check for overflow. I'm just suggesting that it's worth making benchmarks to measure the cost of both.

  21. bstrie commented on Feb 14, 2014

    @bstrie
    Contributor

    There's a lot of interrelated concerns here:

    1. Rust needs to have a type that's as large as a pointer. What should it be named?
    2. What should the "default" integer type be, both for integer literal inference, and for accepting and receiving from stdlib APIs (in order to avoid having to sprinkle casts everywhere)?
    3. Should we prefer to encourage signed ints, or unsigned ints?
    4. To what degree should bigints be a first-class type?
    5. On what types do we want to accept the cost of bounds checking?

    I personally think that int being the default is a mistake, and I've seen a lot of people recoil when they realize that our "default" integer type has both a maximum size after which it wraps and that size varies by architecture. This is the worst of both worlds.

    The easiest way to make immediate progress (not the best, mind you) might be the following:

    1. int -> intptr and uint -> uintptr (let's bikeshed later, we can trivially rename before 1.0, all we need for now is a name that doesn't encourage use).
    2. Convert integer literal inference to make i32 the default integer type (yeah it's super gross, but I really doubt that vast majority of code is going to want to pay for a bigint, and at least this is honest about its limitations).

    This lets us punt on the topics of bigints, bounds checking, and signed vs unsigned for a later date.

  22. thestinger commented on Feb 14, 2014

    @thestinger
    ContributorAuthor

    What should the "default" integer type be, both for integer literal inference, and for accepting and receiving from stdlib APIs (in order to avoid having to sprinkle casts everywhere)?

    I don't think there should be a default fallback, It means you can't trust the compiler to infer the type or give an error, and you have to watch out for bugs from this.

  23. cartazio commented on Feb 14, 2014

    @cartazio
    Contributor

    agree with @thestinger and @bstrie. having defaulting for literals when theres no type constraints is a mixed bag, one hand its great sometimes (but mostly when using a repl). Othertimes its really unclear/confusing what it can mean.

    What about a model where literals are treated as being "polymorphic" if theres no constraints? (this may not make sense in Rust granted), but in haskell / ghc, literals have a generic type until used.

    Prelude> :t 1
    1 :: Num a => a
    
  24. thestinger commented on Feb 14, 2014

    @thestinger
    ContributorAuthor

    Using a fixed-size integer requires carefully considering whether the application enforces bounds on it. Otherwise, you need a big integer instead. A default fallback type removes this thought process in favour of lazy, incorrect code everywhere. Haskell makes the fallback configurable, but the default is a big integer type.

  25. cartazio commented on Feb 14, 2014

    @cartazio
    Contributor

    a wider problem in actual haskell code is users choosing to use Int, and then assuming int is 32 or 64bits always :), but yes, defaulting to integer would be wrong for rust

  26. lilyball commented on Feb 14, 2014

    @lilyball
    Contributor

    i32 does not strike me as a good default. The benefit of using a pointer-sized integer as a default is this same default can be used for indexing (as indexes will want to be pointer-sized). C can get away with using a 4-byte int everywhere because it will silently cast as appropriate, but we can't.

  27. emberian commented on Feb 14, 2014

    @emberian
    Contributor

    i suffix on literals isn't that bad, either... feels a bit strange to go
    back on that though.

    On Fri, Feb 14, 2014 at 3:45 PM, Daniel Micay notifications@github.comwrote:

    Using a fixed-size integer requires carefully considering whether the
    application enforces bounds on it. Otherwise, you need a big integer
    instead. A default fallback type removes this thought process in favour
    of lazy, incorrect code everywhere.

    —
    Reply to this email directly or view it on GitHubhttps://github.com//issues/9940#issuecomment-35122969
    .

  28. nmsmith commented on Feb 14, 2014

    @nmsmith

    I agree that the compiler should not automatically choose an arbitrary, potentially dangerous integer type if it can't infer the type from the context.

  29. l0kod commented on Aug 15, 2014

    @l0kod
    Contributor
  30. added a commit that references this issue on Dec 1, 2022
    ee12b12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions