Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/Default/Decomposers/ArrayDecomposer.cs @ 1463

Last change on this file since 1463 was 1463, checked in by epitzer, 15 years ago

Properly fill arrays with non-zero lower bounds (#561)

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