RFR: JDK-8021560,(str) String constructors that take ByteBuffer
Xueming Shen
xueming.shen at oracle.com
Tue Feb 13 17:00:07 UTC 2018
On 2/13/18, 12:41 AM, Alan Bateman wrote:
>
>> public int getBytes(byte[] dst, int offset, Charset cs);
>> public int getBytes(byte[] dst, int offset, String csname);
>> public int getBytes(ByteBuffer bytes, Charset cs);
>> public int getBytes(ByteBuffer bytes, Charset csn);
> These four methods encode as many characters as possible into the
> destination byte[] or buffer but don't give any indication that the
> destination didn't have enough space to encode the entire string. I
> thus worry they could be a hazard and result in buggy code. If there
> is insufficient space then the user of the API doesn't know how many
> characters were encoded so it's not easy to substring and call
> getBytes again to encode the remaining characters. There is also the
> issue of how to size the destination. What would you think about
> having them fail when there is insufficient space? If they do fail
> then there is a side effect that they will have written to the
> destination so that would need to be documented too.
>
>
Well It's the old "how to control/manage the en/decoding state" issue we
have to deal
with for this kind of apis. I think we faced the similar issue when
designing bae64 de/
encoder.
A possible solution is to return negative value to indicate the
buffer/byte[] provided is
not big enough and its value is the length needed to de/encode the whole
String. So
you can pass in a zero-remaining ByteBuffer or byte[0] to ask for the
size needed, or
we can go even further, take a NULL, like the old C str method to return
the size needed,
though I don't think we want to go that far :-)
That said one of the motivations of these APIs is to easy the use of
doing de/encoding
between ByteBuffer and String, the extra step to handle the "needed
buffer size" appears
to be against the original goal. But the api can always say "please
provide big-enough
buffer, otherwise the method returns the size needed in negative value
and the passed
in buffer might be partially filled ..."
-Sherman
More information about the core-libs-dev
mailing list