JavaXPCOM: How to handle unsigned 8-bit values?
Javier Pedemonte <[email protected]>
| Newsgroups | gmane.comp.mozilla.devel.java |
|---|---|
| Message-ID | <zPKdnSvKEZK4hbDbnZ2dnUVZ_uWlnZ2d__9827.97383699126$1177360538$gmane$org@mozilla.org> |
Java doesn't support unsigned values. However, many of the Mozilla
interfaces take or return unsigned values. The solution in JavaXPCOM
has been to 'promote' the unsigned types to the next larger type in
Java, such that the larger type can handle the full range of the
unsigned type. So, for example, a Mozilla interface that returns an
'unsigned int' in Java is defined to return a 'long'.
But this doesn't work that well for 8-bit (byte) values, since byte
arrays are often used to pass around large chunks of data. Take for
example the nsIWebBrowserStream.appendToStream() function
(http://mxr.mozilla.org/mozilla/source/embedding/browser/webBrowser/nsIWebBrowserStream.idl#73).
According to the XPIDL file, it takes an 'octet' array of data
('octet' is defined in XPIDL as an unsigned 8-bit value).
In Java, it would be natural to want to do something like this:
String htmlData = ...;
byte[] bytes = htmlData.getBytes("UTF-8");
webBrowserStream.appendToStream(bytes, bytes.length);
However, since 'octet' is promoted to the Java 'short', we must first
convert the byte array returned by getBytes() to a short array, before
passing it to appendToStream(). Of course, under the covers, JavaXPCOM
will then convert the short array to a C++ byte array, meaning that in
the end, this array is converted twice to essentially get what we
started with.
I see three ways that JavaXPCOM could handle unsigned values:
1) Promote every XPIDL type to the next larger Java type. This makes it
easiest on the JavaXPCOM user, since they can see the full range of
values and not have to worry about tricks for getting the 'unsigned'
value. However, for 'octet' arrays, it may require to the user to go
through an extra step, as illustrated above.
2) Don't promote anything; C++ type == Java type. This avoids the issue
above. However, the user must now take care when working with unsigned
parameters. In most cases, since they want the actual value, the user
will do the unsigned conversion themselves by putting the value in the
next larger type.
3) Promote everything but 'octet' values. This way, the user doesn't
need to worry about unsigned values, except for byte. And since byte
arrays are often used for passing around data, there is no need to first
copy the data to a short array.
I prefer the 3rd option. What does everyone else here think?
javier pedemonte