1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using HeuristicLab.Persistence.Core;
|
---|
4 | using HeuristicLab.Persistence.Interfaces;
|
---|
5 | using System.Collections.Generic;
|
---|
6 |
|
---|
7 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
8 |
|
---|
9 | public class ArrayDecomposer : IDecomposer {
|
---|
10 |
|
---|
11 | public bool CanDecompose(Type type) {
|
---|
12 | return type.IsArray || type == typeof(Array);
|
---|
13 | }
|
---|
14 |
|
---|
15 | public IEnumerable<Tag> DeCompose(object array) {
|
---|
16 | Array a = (Array)array;
|
---|
17 | yield return new Tag("rank", a.Rank);
|
---|
18 | for (int i = 0; i < a.Rank; i++) {
|
---|
19 | yield return new Tag("length_" + i, a.GetLength(i));
|
---|
20 | }
|
---|
21 | foreach (object o in (Array)array) {
|
---|
22 | yield return new Tag(null, o);
|
---|
23 | }
|
---|
24 | }
|
---|
25 |
|
---|
26 | public object CreateInstance(Type t) {
|
---|
27 | return null;
|
---|
28 | }
|
---|
29 |
|
---|
30 | public object Populate(object instance, IEnumerable<Tag> elements, Type t) {
|
---|
31 | IEnumerator<Tag> e = elements.GetEnumerator();
|
---|
32 | e.MoveNext();
|
---|
33 | int rank = (int)e.Current.Value;
|
---|
34 | int[] lengths = new int[rank];
|
---|
35 | for (int i = 0; i < rank; i++) {
|
---|
36 | e.MoveNext();
|
---|
37 | lengths[i] = (int)e.Current.Value;
|
---|
38 | }
|
---|
39 | Array a = Array.CreateInstance(t.GetElementType(), lengths);
|
---|
40 | int[] positions = new int[rank];
|
---|
41 | while (e.MoveNext()) {
|
---|
42 | int[] currentPositions = positions;
|
---|
43 | e.Current.SafeSet((value) => a.SetValue(value, currentPositions));
|
---|
44 | positions[0] += 1;
|
---|
45 | for (int i = 0; i < rank-1; i++) {
|
---|
46 | if (positions[i] >= lengths[i]) {
|
---|
47 | positions[i] = 0;
|
---|
48 | positions[i + 1] += 1;
|
---|
49 | } else {
|
---|
50 | break;
|
---|
51 | }
|
---|
52 | }
|
---|
53 | }
|
---|
54 | return a;
|
---|
55 | }
|
---|
56 | }
|
---|
57 |
|
---|
58 | }
|
---|