FromStr when there are two modes for parsing a type from a string


#1

In encoding_rs, there are two ways to obtain a &'static Encoding given a label: Encoding::for_label() and Encoding::for_label_no_replacement().

The former returns the replacement encoding for certain labels with which reacting to failure by falling back to another encoding would be dangerous. However, for the callers that react to failure by stopping processing instead of using a fallback, the latter makes more sense.

So which one to use is contextual. If there was a FromStr wrapper for only one of these, it would have to be the former, because using the latter in the wrong context (when reacting to failure by using a fallback) is dangerous.

Is it Rustic to implement FromStr as a wrapper for Encoding::for_label() in this scenario or should it be left unimplemented when there is more than one way to parse a string even if one is preferred?


#2

I’m not aware of any clear idiom for this.

In light of that, especially if you’re looking to coalesce to a stable API, I’d probably take the conservative route and leave off the FromStr impl completely, because that forces your users to make a choice instead of (potentially) automatically falling back to for_label. If you receive feedback from folks that want the FromStr impl, then you’ll have more data and could make the decision to add it. If you start by adding it and come to believe it was a mistake, then removing it (could) be hard.

With that said, that’s kind of hand wavy. I don’t think there’s a clear right answer here!


#3

100% agree. If users need the ability to fit this into something that implements FromStr, you could create a wrapper enum type that implemented the trait, and called the appropriate inner method based on which enum variant you were dealing with.


#4

OK. Thank you. I won’t add FromStr at this time.