lz-string icon indicating copy to clipboard operation
lz-string copied to clipboard

`decompressFromBase64` can return `null`

Open emewjin opened this issue 1 year ago • 7 comments

version: 1.5.0

codesandbox

decompressFromBase64 can return null but it's type definition is export function decompressFromBase64(input: string): string;. image

It should be export function decompressFromBase64(input: string): string | null;

console.log(decompressFromBase64('')) // null

emewjin avatar Dec 15 '23 06:12 emewjin

I never understood why converting an empty string would return null instead of "".

My emotional expectation would be that "" is the return of an empty input and null is returned in the event of an error.

HelloLudger avatar Dec 19 '23 07:12 HelloLudger

@HelloLudger - I think the reason is because an empty string isn't a valid Base64 encoded string. There's no inputs into the Base64 encoding algorithm that generate an empty string so trying to decode an empty string makes no sense. So returning null from the function is a reasonable way to indicate an error due to invalid input.

wkrick avatar Dec 19 '23 16:12 wkrick

@wkrick that would be an explaination, but I found no arguments to support that "" is no valid Base64 (or the other way around).

  • Stack Overflow: https://stackoverflow.com/questions/15212127/is-an-empty-string-valid-base64-encoded-data-of-zero-bytes-length
  • window.atob and window.btoa (who named these functions???) also convert an empty string input to an empty string output.

HelloLudger avatar Dec 20 '23 07:12 HelloLudger

@HelloLudger

Interesting. The test cases proposed in the RFC clearly indicate that encoding an empty string results in an empty string...

BASE64("") = ""

I stand corrected.

wkrick avatar Dec 20 '23 09:12 wkrick

Two issues here, first is code output (and a breaking change) - an empty string is valid for an empty result, an error should be different. Second is that the typings don't match what they should be and isn't breaking (and is also not going to change if / when the code change)

For the empty string result we do need to check it's not breaking in the other implementations otherwise it can't be changed for legacy reasons (and would need to be part of any future plans etc)

Rycochet avatar Dec 24 '23 11:12 Rycochet

Just realised that the typings are correct for v2 - and had a look at some of the implementations for other languages, which have reproduced this behaviour faithfully, so it looks like a very breaking change!

Rycochet avatar Jan 14 '24 11:01 Rycochet

Yes... nothing that could be done without breaking. Only idea I have (and read here before in another context) would be adding mirrored functions with a new systematic of return values. (E.g. compressToBase64Preview)

HelloLudger avatar Jan 15 '24 10:01 HelloLudger