Tanoda
JaggedArray.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using System;
10using UnityEngine;
11
13
14 public class JaggedArray<T> : ISerializationCallbackReceiver {
15
16 [NonSerialized]
17 private T[][] _array;
18
19 [SerializeField]
20 private T[] _data;
21 [SerializeField]
22 private int[] _lengths;
23
24 public JaggedArray() { }
25
26 public JaggedArray(int length) {
27 _array = new T[length][];
28 }
29
30 public JaggedArray(T[][] array) {
31 _array = array;
32 }
33
34 public void OnAfterDeserialize() {
35 _array = new T[_lengths.Length][];
36 int offset = 0;
37 for (int i = 0; i < _lengths.Length; i++) {
38 int length = _lengths[i];
39 if (length == -1) {
40 _array[i] = null;
41 } else {
42 _array[i] = new T[length];
43 Array.Copy(_data, offset, _array[i], 0, length);
44 offset += length;
45 }
46 }
47 }
48
49 public void OnBeforeSerialize() {
50 if (_array == null) {
51 _data = new T[0];
52 _lengths = new int[0];
53 return;
54 }
55
56 int count = 0;
57 foreach (var child in _array) {
58 if (child == null) continue;
59 count += child.Length;
60 }
61
62 _data = new T[count];
63 _lengths = new int[_array.Length];
64 int offset = 0;
65 for (int i = 0; i < _array.Length; i++) {
66 var child = _array[i];
67
68 if (child == null) {
69 _lengths[i] = -1;
70 } else {
71 Array.Copy(child, 0, _data, offset, child.Length);
72 _lengths[i] = child.Length;
73 offset += child.Length;
74 }
75 }
76 }
77
78 public T[] this[int index] {
79 get {
80 return _array[index];
81 }
82 set {
83 _array[index] = value;
84 }
85 }
86
87 public static implicit operator T[][] (JaggedArray<T> jaggedArray) {
88 return jaggedArray._array;
89 }
90
91 public static implicit operator JaggedArray<T>(T[][] array) {
92 return new JaggedArray<T>(array);
93 }
94 }
95}