| 1 |
package combinator |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"reflect" |
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
func Generate(v interface{}, ov interface{}) error { |
| 11 |
|
| 12 |
vPtr := reflect.ValueOf(v) |
| 13 |
if vPtr.Kind() != reflect.Ptr { |
| 14 |
return fmt.Errorf("non-pointer type supplied") |
| 15 |
} |
| 16 |
|
| 17 |
value := vPtr.Elem() |
| 18 |
if value.Kind() != reflect.Slice { |
| 19 |
return fmt.Errorf("pointer to non-slice type supplied") |
| 20 |
} |
| 21 |
vType := reflect.TypeOf(v).Elem().Elem() |
| 22 |
|
| 23 |
ovType := reflect.TypeOf(ov) |
| 24 |
ovValue := reflect.ValueOf(ov) |
| 25 |
if ovValue.Kind() != reflect.Struct { |
| 26 |
return fmt.Errorf("non-slice type supplied") |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
combinations := 1 |
| 31 |
members := ovType.NumField() |
| 32 |
for i := 0; i < members; i++ { |
| 33 |
if ovValue.Field(i).Kind() != reflect.Slice { |
| 34 |
continue |
| 35 |
} |
| 36 |
if ovValue.Field(i).Len() == 0 { |
| 37 |
|
| 38 |
continue |
| 39 |
} |
| 40 |
|
| 41 |
fname := ovType.Field(i).Name |
| 42 |
if _, ok := vType.FieldByName(fname); !ok { |
| 43 |
return fmt.Errorf("can't access struct field %s", fname) |
| 44 |
} |
| 45 |
|
| 46 |
combinations *= ovValue.Field(i).Len() |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
for i := 0; i < combinations; i++ { |
| 51 |
vi := reflect.Indirect(reflect.New(vType)) |
| 52 |
|
| 53 |
offset := 1 |
| 54 |
for j := 0; j < members; j++ { |
| 55 |
ovf := ovValue.Field(j) |
| 56 |
var fvalue reflect.Value |
| 57 |
|
| 58 |
if ovf.Kind() == reflect.Slice { |
| 59 |
if ovf.Len() == 0 { |
| 60 |
|
| 61 |
continue |
| 62 |
} |
| 63 |
|
| 64 |
fvalue = ovf.Index((i / offset) % ovf.Len()) |
| 65 |
offset *= ovf.Len() |
| 66 |
} else { |
| 67 |
fvalue = ovf |
| 68 |
} |
| 69 |
|
| 70 |
fname := ovType.Field(j).Name |
| 71 |
if vi.FieldByName(fname).CanSet() { |
| 72 |
vi.FieldByName(fname).Set(fvalue) |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
value.Set(reflect.Append(value, vi)) |
| 80 |
} |
| 81 |
|
| 82 |
return nil |
| 83 |
} |