discuss-gnustep
[Top][All Lists]
Advanced

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

Re: NSInteger vs. NSUInteger


From: Sebastian Reitenbach
Subject: Re: NSInteger vs. NSUInteger
Date: Sun, 10 Feb 2013 12:23:25 +0100
User-agent: SOGoMail 2.0.4b

 
On Sunday, February 10, 2013 07:37 CET, Richard Frith-Macdonald 
<richard@tiptree.demon.co.uk> wrote: 
 
> 
> On 9 Feb 2013, at 18:11, Sebastian Reitenbach wrote:
> 
> > Hi,
> > 
> > when I see something like this for example in ProjectCenter:
> > 
> > - (NSInteger)numberOfRowsInTableView: (NSTableView *)aTableView
> > {
> >  return [docTypesItems count];
> > }
> > 
> > where docTypesItems is a NSMutableArray. I see many of the GUI elements
> > use NSInteger. But for example NSArray, or NSDictionary count return
> > NSUInteger.
> > 
> > When I see above statement, how is best way to proceed to not for
> > example return a too large NSUInteger, which would convert into
> > a negative NSInteger?
> > 
> > Since most of the time I see contents of tables, browsers and whatnot
> > stored in NSArrays or NSDictionaries, nearly everywhere I came across
> > I see this potential trouble with the signed vs. unsigned 
> > discrepancies when setting it up in the GUI.
> > 
> > Also often I see some of those results then compared, actually comparing
> > a NSUInteger against a NSInteger. When one is too large, or the other
> > negative, funny things may happen.
> > 
> > Is there some best practices, how to handle that? Or is there something in
> > the runtime, I am not aware of, that takes care about it?
> 
> Well, there are two good things:
> 
> 1. A direct equality test against NSNotFound will work for both NSInteger and 
> NSUInteger, so that's OK.

yeah, that is also fine with me ;)

> 
> 2. in most contexts in the GUI, it's safe to assume that no data structure 
> will contain more than two billion (2^31) elements  ... so you don't have to 
> worry about things like array counts returning values which would turn 
> negative when converted.  Generally, if you had anything even remotely close 
> to that number of elements in a GUI data structure, your app would be 
> effectively dead anyway.

Yeah, I assumed that, in normal cases it should not matter. But what if someone 
accidently or maliciously creates around 2^31 files in a directory, and then 
the file browser chokes on that?

> 
> Anywhere that those two cases don't apply, you need to check the value of 
> NSUInteger before you treat it as an NSInteger.
> So, while it's good to review these cases, and important to treat them with 
> care, it's usually fine to simply cast the unsigned value to be a signed one.
> 

So, when I assume to be surrounded by malicious people, I probably should 
always check, regardless where the input
comes from,  otherwise, assuming friendly people, I probably can assume to be 
safe most of the times.

thanks,
Sebastian




reply via email to

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