1 /* Copyright (C) 2004 - 2009  Versant Inc.  http://www.db4o.com */
2 
3 using System;
4 using System.Collections;
5 using Db4objects.Db4o.Foundation;
6 
7 namespace Db4objects.Db4o.Foundation
8 {
9 	/// <exclude></exclude>
10 	public class SortedCollection4
11 	{
12 		private readonly IComparison4 _comparison;
13 
14 		private Tree _tree;
15 
SortedCollection4(IComparison4 comparison)16 		public SortedCollection4(IComparison4 comparison)
17 		{
18 			if (null == comparison)
19 			{
20 				throw new ArgumentNullException();
21 			}
22 			_comparison = comparison;
23 			_tree = null;
24 		}
25 
SingleElement()26 		public virtual object SingleElement()
27 		{
28 			if (1 != Size())
29 			{
30 				throw new InvalidOperationException();
31 			}
32 			return _tree.Key();
33 		}
34 
AddAll(IEnumerator iterator)35 		public virtual void AddAll(IEnumerator iterator)
36 		{
37 			while (iterator.MoveNext())
38 			{
39 				Add(iterator.Current);
40 			}
41 		}
42 
Add(object element)43 		public virtual void Add(object element)
44 		{
45 			_tree = Tree.Add(_tree, new TreeObject(element, _comparison));
46 		}
47 
Remove(object element)48 		public virtual void Remove(object element)
49 		{
50 			_tree = Tree.RemoveLike(_tree, new TreeObject(element, _comparison));
51 		}
52 
ToArray(object[] array)53 		public virtual object[] ToArray(object[] array)
54 		{
55 			Tree.Traverse(_tree, new _IVisitor4_43(array));
56 			return array;
57 		}
58 
59 		private sealed class _IVisitor4_43 : IVisitor4
60 		{
_IVisitor4_43(object[] array)61 			public _IVisitor4_43(object[] array)
62 			{
63 				this.array = array;
64 				this.i = 0;
65 			}
66 
67 			internal int i;
68 
Visit(object obj)69 			public void Visit(object obj)
70 			{
71 				array[this.i++] = ((TreeObject)obj).Key();
72 			}
73 
74 			private readonly object[] array;
75 		}
76 
Size()77 		public virtual int Size()
78 		{
79 			return Tree.Size(_tree);
80 		}
81 	}
82 }
83