ccollins476ad commented on a change in pull request #266: `newt target dump` command URL: https://github.com/apache/mynewt-newt/pull/266#discussion_r256549354
########## File path: newt/syscfg/restrict.go ########## @@ -82,6 +84,48 @@ type CfgRestriction struct { Expr string } +func (c CfgRestrictionCode) String() string { + for s, code := range cfgRestrictionNameCodeMap { + if code == c { + return s + } + } + + return "???" +} + +func parseCfgRestrictionCode(s string) (CfgRestrictionCode, error) { + if c, ok := cfgRestrictionNameCodeMap[s]; ok { + return c, nil + } + + return 0, util.FmtNewtError("cannot parse cfg restriction code \"%s\"", s) +} + +func (c CfgRestrictionCode) MarshalJSON() ([]byte, error) { + s := c.String() + j, err := json.Marshal(s) + if err != nil { + return nil, util.ChildNewtError(err) + } + return j, nil +} + +func (c *CfgRestrictionCode) UnmarshalJSON(b []byte) error { Review comment: That's a good idea! I think we could eliminate a lot of duplication with something like this: ``` func MarshalJSONStringer(sr fmt.Stringer) ([]byte, error) { s := sr.String() j, err := json.Marshal(s) if err != nil { return nil, ChildNewtError(err) } return j, nil } ``` (`fmt.Stringer` is an interface that supports the `String()` function). Then the `CfgRestrictionCode` `MarshalJSON` function becomes: ``` func (c CfgRestrictionCode) MarshalJSON() ([]byte, error) { return util.MarshalJSONStringer(c) } ``` Unfortunately, I don't think we can do something similar for the unmarshal functions. The problem is that each unmarshal function needs to return a different type, and Go doesn't support generics. Still, eliminating the duplication in all the marshal functions is great. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services