|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package genai |
| 16 | + |
| 17 | +import ( |
| 18 | + "encoding/json" |
| 19 | + "fmt" |
| 20 | + "strconv" |
| 21 | +) |
| 22 | + |
| 23 | +type int64sFromStringSlice []int64 |
| 24 | + |
| 25 | +func (s *int64sFromStringSlice) UnmarshalJSON(data []byte) error { |
| 26 | + var stringSlice []string |
| 27 | + if err := json.Unmarshal(data, &stringSlice); err != nil { |
| 28 | + // If both attempts fail, return a more informative error |
| 29 | + return fmt.Errorf("failed to unmarshal as []int64 or []string: %w", err) |
| 30 | + } |
| 31 | + |
| 32 | + // If successful as a []string, convert each element to int64 |
| 33 | + result := make([]int64, 0, len(stringSlice)) |
| 34 | + for _, str := range stringSlice { |
| 35 | + val, err := strconv.ParseInt(str, 10, 64) |
| 36 | + if err != nil { |
| 37 | + return err // Error during string-to-int conversion |
| 38 | + } |
| 39 | + result = append(result, val) |
| 40 | + } |
| 41 | + |
| 42 | + *s = result |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +func (s int64sFromStringSlice) MarshalJSON() ([]byte, error) { |
| 47 | + stringSlice := make([]string, 0, len(s)) |
| 48 | + for _, val := range s { |
| 49 | + stringSlice = append(stringSlice, strconv.FormatInt(val, 10)) |
| 50 | + } |
| 51 | + return json.Marshal(stringSlice) |
| 52 | +} |
0 commit comments