Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Default/Decomposers/ArrayDecomposer.cs @ 1434

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

Almost complete solution for correctly handling parent references. (#506)

File size: 1.7 KB
Line 
1using System;
2using System.Collections;
3using HeuristicLab.Persistence.Core;
4using HeuristicLab.Persistence.Interfaces;
5using System.Collections.Generic;
6
7namespace 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}
Note: See TracBrowser for help on using the repository browser.