Skip to content
This repository has been archived by the owner on Nov 12, 2022. It is now read-only.

Optional Conversions to and from Values #545

Closed
Redfire75369 opened this issue Jul 3, 2021 · 4 comments
Closed

Optional Conversions to and from Values #545

Redfire75369 opened this issue Jul 3, 2021 · 4 comments

Comments

@Redfire75369
Copy link
Contributor

I will be working on a pull request for this soon, but decided to ask here for any comments first.

This issue involves adding an impl<T: ToJSValConvertible> ToJSValConvertible for Option<T> and impl<T: FromJSValConvertible> FromJSValConvertible for Option<T>.

Reason

This will be helpful for creating methods with optional parameters, such as console.assert, and more closely allow for the reproduction of javascript function calls, which can accept any number of parameters, regardless of the number specified in the definition.

FromJSValConvertible

When the Value is undefined, the method will return None and will return Some(x) otherwise.

ToJSValConvertible

When the value is None, the method will return undefined as a Value and the regular value otherwise.

@jdm
Copy link
Member

jdm commented Jul 3, 2021

These changes sound reasonable!

@Redfire75369
Copy link
Contributor Author

Redfire75369 commented Jul 4, 2021

I am looking through the code currently, and it seems that both of these are already implemented. However, it also seems that ToJSValConvertible for None returns null, instead of undefined. This behaviour may need to be reconsidered.

@jdm
Copy link
Member

jdm commented Jul 4, 2021

Oh, that's a good point. Changing that would almost certainly imapact web-visible code in Servo, and I think the current behaviour makes sense. You could try creating a struct Undefinable<T>(Option<T>) and implement ToJSValConvertible for Undefinable in your own crate.

@Redfire75369
Copy link
Contributor Author

I think I shall leave the behaviour as it stands currently, and add Nullable<T> and Undefinable<T> if I require, later.
Null is something that does not exist and is returned explicitly (generally), while undefined is something that does not exist and is returned implicitly (e.g. function with no return statement). It makes sense that explicitly returning a Option<T> from rust, would result in null instead of undefined.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants