#2587 Buf.toImmutable()

SlimerDude Tue 27 Dec 2016

As recently mentioned, Buf now implements .toImmutable().

For those who aren't aware it returns a new const Buf but with the caveat of all the data in the original Buf being cleared. This is to allow the backing array to be copied from the 1st Buf to the 2nd, making the operation very cheap.

It's a handy method and I've used Buf.toImmutable() a few times already, but I must say I really don't like how the original Buf suddenly looses all data when toImmutable() is called. I find the behaviour unexpected as it is different to other .toImmutable() implementations such as List and Map. And, to be honest, has caused me some data loss when I continued to use the original Buf instance when unbeknownst to me, it no longer contained any data!

I understand the necessity of the cheap copy and I understand why the array can not be shared, but may I propose that instead of simply clearing the data, a flag is set in the original Buf that makes it unusable. So that any method called on the Buf results in an Err being thrown: This Buf instance has been rendered unusable following a call to toImmutable().

Should the instance continue to be used, it is then clear to the caller what has happened.

Should you need to continue using the same Buf instance, maybe a manual explicit call to clear() could reset the error flag and make it usable again.

Login or Signup to reply.