conversionCode produces the code that converts the string contained in the variable named from to the value stored in the variable "to" of type typeName. The second return value indicates whether the "err" variable must be declared prior to the conversion code being rendered. The last return value i
(from, to, typeName string, pointer bool)
| 493 | // value indicates whether the generated code can produce errors (i.e. |
| 494 | // initialize the err variable). |
| 495 | func conversionCode(from, to, typeName string, pointer bool) (string, bool, bool) { |
| 496 | var ( |
| 497 | parse string |
| 498 | cast string |
| 499 | |
| 500 | target = to |
| 501 | needCast = typeName != stringN && typeName != bytesN && flagType(typeName) != "JSON" |
| 502 | declErr = true |
| 503 | checkErr = true |
| 504 | decl = "" |
| 505 | ) |
| 506 | if needCast && pointer { |
| 507 | target = "val" |
| 508 | decl = ":" |
| 509 | } |
| 510 | switch typeName { |
| 511 | case boolN: |
| 512 | if pointer { |
| 513 | parse = fmt.Sprintf("var %s bool\n", target) |
| 514 | } |
| 515 | parse += fmt.Sprintf("%s, err = strconv.ParseBool(%s)", target, from) |
| 516 | case intN: |
| 517 | parse = fmt.Sprintf("var v int64\nv, err = strconv.ParseInt(%s, 10, strconv.IntSize)", from) |
| 518 | cast = fmt.Sprintf("%s %s= int(v)", target, decl) |
| 519 | case int32N: |
| 520 | parse = fmt.Sprintf("var v int64\nv, err = strconv.ParseInt(%s, 10, 32)", from) |
| 521 | cast = fmt.Sprintf("%s %s= int32(v)", target, decl) |
| 522 | case int64N: |
| 523 | parse = fmt.Sprintf("%s, err %s= strconv.ParseInt(%s, 10, 64)", target, decl, from) |
| 524 | declErr = decl == "" |
| 525 | case uintN: |
| 526 | parse = fmt.Sprintf("var v uint64\nv, err = strconv.ParseUint(%s, 10, strconv.IntSize)", from) |
| 527 | cast = fmt.Sprintf("%s %s= uint(v)", target, decl) |
| 528 | case uint32N: |
| 529 | parse = fmt.Sprintf("var v uint64\nv, err = strconv.ParseUint(%s, 10, 32)", from) |
| 530 | cast = fmt.Sprintf("%s %s= uint32(v)", target, decl) |
| 531 | case uint64N: |
| 532 | parse = fmt.Sprintf("%s, err %s= strconv.ParseUint(%s, 10, 64)", target, decl, from) |
| 533 | declErr = decl == "" |
| 534 | case float32N: |
| 535 | parse = fmt.Sprintf("var v float64\nv, err = strconv.ParseFloat(%s, 32)", from) |
| 536 | cast = fmt.Sprintf("%s %s= float32(v)", target, decl) |
| 537 | case float64N: |
| 538 | parse = fmt.Sprintf("%s, err %s= strconv.ParseFloat(%s, 64)", target, decl, from) |
| 539 | declErr = decl == "" |
| 540 | case stringN: |
| 541 | parse = fmt.Sprintf("%s %s= %s", target, decl, from) |
| 542 | declErr = false |
| 543 | checkErr = false |
| 544 | case bytesN: |
| 545 | parse = fmt.Sprintf("%s %s= []byte(%s)", target, decl, from) |
| 546 | declErr = false |
| 547 | checkErr = false |
| 548 | default: |
| 549 | parse = fmt.Sprintf("err = json.Unmarshal([]byte(%s), &%s)", from, target) |
| 550 | } |
| 551 | if !needCast { |
| 552 | return parse, declErr, checkErr |
no test coverage detected