├── .gitignore
├── .nuget
└── packages.config
├── CSharpTest.Net.Collections.nuspec
├── CSharpTest.Net.Collections.sln
├── README.md
├── packages
└── repositories.config
└── src
├── CSharpTest.Net.BPlusTreeTest
├── Bases
│ └── Comparable.cs
├── BasicMemoryTests.cs
├── BasicTests.cs
├── BasicTestsVersion2.cs
├── CSharpTest.Net.BPlusTree.Test.csproj
├── Crypto
│ └── Hash.cs
├── Reflection
│ ├── PropertyType.cs
│ └── PropertyValue.cs
├── SampleCustomTypeTest.cs
├── SampleTypes
│ ├── DataValue.cs
│ ├── DataValueSerializer.cs
│ ├── KeyInfo.cs
│ ├── KeyInfoComparer.cs
│ └── KeyInfoSerializer.cs
├── SequenceTests.cs
├── Shared
│ └── Check.cs
├── TestBPlusTreeOptions.cs
├── TestBackupAndRecovery.cs
├── TestBulkInsert.cs
├── TestCollection.cs
├── TestCustomStorage.cs
├── TestDictionary.cs
├── TestFileSerialized.cs
├── TestInfo.cs
├── TestMultiInstance.cs
├── TestSimpleDictionary.cs
├── TestTransactionLog.cs
├── ThreadedBTreeTest.cs
├── ThreadedMassInsertTest.cs
├── Threading
│ ├── IWorkQueue.cs
│ └── WorkQueue.cs
└── packages.config
├── CSharpTest.Net.Collections
├── Bases
│ ├── Disposable.cs
│ └── Equatable.cs
├── CSharpTest.Net.Collections.csproj
├── CmdTool.config
├── Collections
│ ├── BPlusTree.Debug.cs
│ ├── BPlusTree.Options.cs
│ ├── BPlusTree.OptionsBase.cs
│ ├── BPlusTree.Recovery.cs
│ ├── BPlusTree.cs
│ ├── BTreeDictionary.cs
│ ├── BTreeList.cs
│ ├── DisposingList.cs
│ ├── Element.cs
│ ├── Enumerator.cs
│ ├── HashUtilities.cs
│ ├── IConcurrentDictionary.cs
│ ├── IDictionaryEx.cs
│ ├── Interfaces.cs
│ ├── KeyValueComparer.cs
│ ├── LurchTable.cs
│ ├── MergeSort.cs
│ ├── Node.BulkInsert.cs
│ ├── Node.Delete.cs
│ ├── Node.Insert.cs
│ ├── Node.Search.cs
│ ├── Node.Serialize.cs
│ ├── Node.cs
│ ├── NodeCache.Base.cs
│ ├── NodeCache.Full.cs
│ ├── NodeCache.None.cs
│ ├── NodeCache.Normal.cs
│ ├── NodeHandle.cs
│ ├── NodePin.cs
│ ├── NodeTransaction.cs
│ ├── OrderedEnumeration.cs
│ ├── OrderedKeyValuePairs.cs
│ ├── OrdinalList.cs
│ ├── SetList.cs
│ └── TransactionLog.cs
├── Exceptions.cs
├── IO
│ ├── AggregateStream.cs
│ ├── BinaryComparer.cs
│ ├── Crc32.cs
│ ├── FileStreamFactory.cs
│ ├── FragmentedFile.cs
│ ├── IOStream.cs
│ ├── StreamCache.cs
│ ├── TempFile.cs
│ └── TransactedCompoundFile.cs
├── Interfaces
│ ├── DefaultFactories.cs
│ ├── ICloneable.cs
│ ├── IFactory.cs
│ └── ITransactable.cs
├── LICENSE-2.0.txt
├── Properties
│ └── AssemblyInfo.cs
├── README.htm
├── Resources.Designer.cs
├── Resources.resx
├── Serialization
│ ├── ISerializer.cs
│ ├── KeyValueSerializer.cs
│ ├── LimitedSerializer.cs
│ ├── PrimitiveSerializer.cs
│ └── VariantNumberSerializer.cs
├── Storage
│ ├── Storage.Cache.cs
│ ├── Storage.Disk.cs
│ ├── Storage.DiskV2.cs
│ └── Storage.Memory.cs
├── Synchronization
│ ├── ExclusiveLocking.cs
│ ├── ILockStrategy.cs
│ ├── IgnoreLocking.cs
│ ├── LockFactory.cs
│ ├── ReadLock.cs
│ ├── ReaderWriterLocking.cs
│ ├── SafeLock.cs
│ ├── SimpleReadWriteLocking.cs
│ ├── WriteLock.cs
│ └── WriterOnlyLocking.cs
└── Utils
│ ├── Check.cs
│ ├── ObjectKeepAlive.cs
│ └── WeakReference.cs
└── CSharpTest.Net.CollectionsTest
├── Bases
├── Comparable.cs
├── Disposable.cs
└── Equatable.cs
├── CSharpTest.Net.Collections.Test.csproj
├── ExampleCode.cs
├── IO
├── SegmentedMemoryStream.cs
└── SharedMemoryStream.cs
├── LockingTests
├── BaseLockTest.cs
├── BaseThreadedReaderWriterTest.cs
├── BaseThreadedWriterTest.cs
├── TestExclusiveLocking.cs
├── TestIgnoreLocking.cs
├── TestLockingStructs.cs
├── TestReaderWriterLocking.cs
├── TestReservedWriteLocking.cs
├── TestSimpleReadWriteLocking.cs
├── TestWriterOnlyLocking.cs
└── ThreadedReaderWriter.cs
├── Shared
└── Check.cs
├── SynchronizedDictionary.cs
├── TestBTreeDictionary.cs
├── TestBTreeList.cs
├── TestBinaryComparer.cs
├── TestCrc32.cs
├── TestDisposable.cs
├── TestDisposingList.cs
├── TestEquatable.cs
├── TestFactories.cs
├── TestFragmentedFile.cs
├── TestGenericCollection.cs
├── TestLurchTable.cs
├── TestLurchTableThreading.cs
├── TestObjectKeepAlive.cs
├── TestOrderedEnumeration.cs
├── TestOrdinalList.cs
├── TestPrimitiveSerializer.cs
├── TestSetList.cs
├── TestStreamCache.cs
├── TestTempFiles.cs
├── TestTransactedCompoundFile.cs
├── TestVariantSerializer.cs
├── TestWeakReferenceT.cs
├── TestWorkQueue.cs
├── Threading
├── IWorkQueue.cs
└── WorkQueue.cs
└── packages.config
/.gitignore:
--------------------------------------------------------------------------------
1 | _ReSharper.*
2 | obj
3 | bin
4 | Bin
5 | Debug
6 | Release
7 | *.user
8 | *.pdb
9 | *.suo
10 | *.sln
11 | *.DotSettings
12 | *.Generated.cs
13 | *.cache
14 | *.vspscc
15 | *.log
16 | *.ncb
17 | *.pch
18 | *.sdf
19 | *.zip
20 | *.mdf
21 | *.snk
22 |
23 | packages/*/*
24 | depend/*
--------------------------------------------------------------------------------
/.nuget/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/CSharpTest.Net.Collections.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 | $version$
9 | CSharpTest.Net.Collections
10 | CSharpTest.Net.Collections
11 | Roger Knapp
12 | Roger Knapp
13 | en-US
14 | http://csharptest.net/src/LICENSE-2.0.txt
15 | https://github.com/csharptest/CSharpTest.Net.Collections
16 | http://csharptest.net/favicon.ico
17 | false
18 | Copyright 2008-2011 by Roger Knapp, Licensed under the Apache License, Version 2.0
19 |
20 | B+ Tree BPlus BTree BPlusTree LinkedHashMap Dictionary Binary File Storage
21 | CSharpTest.Net.Collections is a small set of generic collections for .NET, including in-memory or disk-based B+Tree, LurchTable for LRU caching, MergeSort and others.
22 | See the main project page (https://github.com/csharptest/CSharpTest.Net.Collections) for release notes.
23 |
24 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/CSharpTest.Net.Collections.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpTest.Net.Collections", "src\CSharpTest.Net.Collections\CSharpTest.Net.Collections.csproj", "{FBD5EDD1-445C-46D1-A0B2-4B68CB51EADB}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpTest.Net.BPlusTree.Test", "src\CSharpTest.Net.BPlusTreeTest\CSharpTest.Net.BPlusTree.Test.csproj", "{F97601FB-7E62-47DA-8E48-B56C9AD5DF20}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpTest.Net.Collections.Test", "src\CSharpTest.Net.CollectionsTest\CSharpTest.Net.Collections.Test.csproj", "{097601FB-7E62-47DA-8E48-B56C9AD5DF20}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{794876C0-9497-427F-922C-26B92DA08A73}"
11 | ProjectSection(SolutionItems) = preProject
12 | .nuget\packages.config = .nuget\packages.config
13 | EndProjectSection
14 | EndProject
15 | Global
16 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
17 | Debug|Any CPU = Debug|Any CPU
18 | Release|Any CPU = Release|Any CPU
19 | EndGlobalSection
20 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
21 | {FBD5EDD1-445C-46D1-A0B2-4B68CB51EADB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22 | {FBD5EDD1-445C-46D1-A0B2-4B68CB51EADB}.Debug|Any CPU.Build.0 = Debug|Any CPU
23 | {FBD5EDD1-445C-46D1-A0B2-4B68CB51EADB}.Release|Any CPU.ActiveCfg = Release|Any CPU
24 | {FBD5EDD1-445C-46D1-A0B2-4B68CB51EADB}.Release|Any CPU.Build.0 = Release|Any CPU
25 | {F97601FB-7E62-47DA-8E48-B56C9AD5DF20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26 | {F97601FB-7E62-47DA-8E48-B56C9AD5DF20}.Debug|Any CPU.Build.0 = Debug|Any CPU
27 | {F97601FB-7E62-47DA-8E48-B56C9AD5DF20}.Release|Any CPU.ActiveCfg = Release|Any CPU
28 | {F97601FB-7E62-47DA-8E48-B56C9AD5DF20}.Release|Any CPU.Build.0 = Release|Any CPU
29 | {097601FB-7E62-47DA-8E48-B56C9AD5DF20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
30 | {097601FB-7E62-47DA-8E48-B56C9AD5DF20}.Debug|Any CPU.Build.0 = Debug|Any CPU
31 | {097601FB-7E62-47DA-8E48-B56C9AD5DF20}.Release|Any CPU.ActiveCfg = Release|Any CPU
32 | {097601FB-7E62-47DA-8E48-B56C9AD5DF20}.Release|Any CPU.Build.0 = Release|Any CPU
33 | EndGlobalSection
34 | GlobalSection(SolutionProperties) = preSolution
35 | HideSolutionNode = FALSE
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | CSharpTest.Net.Collections
2 | =======================
3 |
4 | CSharpTest.Net.Collections (moved from https://code.google.com/p/csharptest-net/)
5 |
6 | ## Change Log ##
7 |
8 | 2014-09-06 Initial clone and extraction from existing library.
9 |
10 | ## Online Help ##
11 |
12 | BPlusTree Help: http://help.csharptest.net/?CSharpTest.Net.BPlusTree~CSharpTest.Net.Collections.BPlusTree%602.html
13 |
14 | ## Quick start ##
15 |
16 | ### LurchTable Example ###
17 | ```
18 | //Example producer/consumer queue where producer threads help when queue is full
19 | using (var queue = new LurchTable(LurchTableOrder.Insertion, 100))
20 | {
21 | var stop = new ManualResetEvent(false);
22 | queue.ItemRemoved += kv => Console.WriteLine("[{0}] - {1}", Thread.CurrentThread.ManagedThreadId, kv.Key);
23 | //start some threads eating queue:
24 | var thread = new Thread(() => { while (!stop.WaitOne(0)) queue.Dequeue(); })
25 | { Name = "worker", IsBackground = true };
26 | thread.Start();
27 |
28 | var names = Directory.GetFiles(Path.GetTempPath(), "*", SearchOption.AllDirectories);
29 | if (names.Length <= 100) throw new Exception("Not enough trash in your temp dir.");
30 | var loops = Math.Max(1, 10000/names.Length);
31 | for(int i=0; i < loops; i++)
32 | foreach (var name in names)
33 | queue[name] = i;
34 |
35 | stop.Set();
36 | thread.Join();
37 | }
38 | ```
39 |
40 | ### BPlusTree Example ###
41 | ```
42 | var options = new BPlusTree.OptionsV2(PrimitiveSerializer.String, PrimitiveSerializer.DateTime);
43 | options.CalcBTreeOrder(16, 24);
44 | options.CreateFile = CreatePolicy.Always;
45 | options.FileName = Path.GetTempFileName();
46 | using (var tree = new BPlusTree(options))
47 | {
48 | var tempDir = new DirectoryInfo(Path.GetTempPath());
49 | foreach (var file in tempDir.GetFiles("*", SearchOption.AllDirectories))
50 | {
51 | tree.Add(file.FullName, file.LastWriteTimeUtc);
52 | }
53 | }
54 | options.CreateFile = CreatePolicy.Never;
55 | using (var tree = new BPlusTree(options))
56 | {
57 | var tempDir = new DirectoryInfo(Path.GetTempPath());
58 | foreach (var file in tempDir.GetFiles("*", SearchOption.AllDirectories))
59 | {
60 | DateTime cmpDate;
61 | if (!tree.TryGetValue(file.FullName, out cmpDate))
62 | Console.WriteLine("New file: {0}", file.FullName);
63 | else if (cmpDate != file.LastWriteTimeUtc)
64 | Console.WriteLine("Modified: {0}", file.FullName);
65 | tree.Remove(file.FullName);
66 | }
67 | foreach (var item in tree)
68 | {
69 | Console.WriteLine("Removed: {0}", item.Key);
70 | }
71 | }
72 | ```
73 |
--------------------------------------------------------------------------------
/packages/repositories.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/Bases/Comparable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Diagnostics;
18 | using System.ComponentModel;
19 |
20 | namespace CSharpTest.Net.Bases
21 | {
22 | /// Provides a base-class for non-reference comparison of objects
23 | [System.Diagnostics.DebuggerNonUserCode]
24 | public abstract class Comparable : Equatable, IComparable, IComparable
25 | where T : Comparable
26 | {
27 | /// returns a non-reference comparer for this class
28 | public static new readonly EqualityComparer Comparer = new EqualityComparer();
29 |
30 | /// Returns true if the object is equal
31 | public override bool Equals(T other)
32 | { return ((object)other) == null ? false : (0 == this.CompareTo(other)); }
33 |
34 | /// Compares with another object of T
35 | public abstract int CompareTo(T other);
36 |
37 | int IComparable.CompareTo(object obj)
38 | { return this.CompareTo(obj as T); }
39 |
40 | /// Compares two objects
41 | public static bool operator <(Comparable a, Comparable b)
42 | {
43 | return Comparer.Compare(a as T, b as T) < 0;
44 | }
45 | /// Compares two objects
46 | public static bool operator <=(Comparable a, Comparable b)
47 | {
48 | return Comparer.Compare(a as T, b as T) <= 0;
49 | }
50 | /// Compares two objects
51 | public static bool operator >(Comparable a, Comparable b)
52 | {
53 | return Comparer.Compare(a as T, b as T) > 0;
54 | }
55 | /// Compares two objects
56 | public static bool operator >=(Comparable a, Comparable b)
57 | {
58 | return Comparer.Compare(a as T, b as T) >= 0;
59 | }
60 |
61 | /// Implements the equality comparer
62 | [System.Diagnostics.DebuggerNonUserCode]
63 | public sealed new class EqualityComparer : Comparer, IEqualityComparer, IComparer
64 | {
65 | /// Compares the two objects for non-reference equality
66 | public bool Equals(T x, T y)
67 | {
68 | if (((object)x) == null) return ((object)y) == null;
69 | if (((object)y) == null) return false;
70 | return 0 == x.CompareTo(y);
71 | }
72 | /// Extracts the correct hash code
73 | public int GetHashCode(T obj)
74 | {
75 | return ((object)obj) == null ? 0 : obj.HashCode;
76 | }
77 | /// Returns the comparison between the two objects
78 | public override int Compare(T x, T y)
79 | {
80 | if (((object)x) == null) return ((object)y) == null ? 0 : -1;
81 | if (((object)y) == null) return 1;
82 | return x.CompareTo(y);
83 | }
84 |
85 | #region Hide base-members
86 | #if false
87 | private const string ERROR = "This method should not be called.";
88 |
89 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
90 | public static new bool ReferenceEquals(object x, object y) { return Object.ReferenceEquals(x, y); }
91 |
92 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
93 | public static new bool Equals(object x, object y) { return Object.Equals(x, y); }
94 |
95 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
96 | public new bool Equals(object obj) { return base.Equals(obj); }
97 |
98 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
99 | public new int GetHashCode() { return base.GetHashCode(); }
100 |
101 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
102 | public new string ToString() { return base.ToString(); }
103 |
104 | [Obsolete(ERROR, true), DebuggerHidden, EditorBrowsable(EditorBrowsableState.Never)]
105 | public new Type GetType() { return base.GetType(); }
106 | #endif
107 | #endregion
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/BasicMemoryTests.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using NUnit.Framework;
18 | using CSharpTest.Net.Collections;
19 |
20 | namespace CSharpTest.Net.BPlusTree.Test
21 | {
22 | [TestFixture]
23 | public partial class BasicMemoryTests : BasicTests
24 | {
25 | protected override BPlusTree Create(BPlusTreeOptions options)
26 | {
27 | // Test with all-default in-memory ctor
28 | return new BPlusTree();
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/CSharpTest.Net.BPlusTree.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 9.0.30729
7 | 2.0
8 | {F97601FB-7E62-47DA-8E48-B56C9AD5DF20}
9 | Library
10 | CSharpTest.Net.BPlusTree.Test
11 | CSharpTest.Net.BPlusTree.Test
12 | v2.0
13 | 512
14 |
15 |
16 |
17 | True
18 | pdbonly
19 | false
20 | bin\
21 | DEBUG;TRACE
22 | none
23 | 4
24 | true
25 |
26 |
27 | True
28 | pdbonly
29 | true
30 | bin\
31 | TRACE
32 | none
33 | 4
34 | true
35 |
36 |
37 |
38 | ..\..\packages\NUnit.2.6.3\lib\nunit.framework.dll
39 |
40 |
41 |
42 | False
43 | False
44 |
45 |
46 |
47 |
48 |
49 | {fbd5edd1-445c-46d1-a0b2-4b68cb51eadb}
50 | CSharpTest.Net.Collections
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | Code
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/Reflection/PropertyValue.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2009-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.Reflection
19 | {
20 | ///
21 | /// Allows setting or getting a property or field of a known type on an object via reflection
22 | ///
23 | public class PropertyValue : PropertyValue
24 | {
25 | ///
26 | /// Provided an instance of an object and the name of a property/field this object
27 | /// allows you to set/get the value in that property/field
28 | ///
29 | /// An instance of an object to retrieve the property/field from
30 | /// The name of the property or field
31 | public PropertyValue(object instance, string name)
32 | : base(instance, name)
33 | {
34 | Check.IsAssignable(typeof(T), base.Type);
35 | }
36 |
37 | ///
38 | /// Gets or sets the value of the property
39 | ///
40 | public new T Value
41 | {
42 | get { return (T)base.Value; }
43 | set { base.Value = value; }
44 | }
45 | }
46 |
47 | ///
48 | /// Allows setting or getting a property or field on an object via reflection
49 | ///
50 | public class PropertyValue : PropertyType
51 | {
52 | private readonly object _instance;
53 |
54 | ///
55 | /// Provided an instance of an object and the name of a property/field this object
56 | /// allows you to set/get the value in that property/field
57 | ///
58 | /// An instance of an object to retrieve the property/field from
59 | /// The name of the property or field
60 | public PropertyValue(object instance, string name)
61 | : base(Check.NotNull(instance).GetType(), name)
62 | {
63 | _instance = Check.NotNull(instance);
64 | }
65 |
66 | ///
67 | /// Gets or sets the value of the property
68 | ///
69 | public object Value
70 | {
71 | get
72 | {
73 | return base.GetValue(_instance);
74 | }
75 | set
76 | {
77 | base.SetValue(_instance, Check.IsAssignable(this.Type, value));
78 | }
79 | }
80 |
81 | ///
82 | /// Walks a heirarchy of properties from the given type down. You can specify in any of the
83 | /// following ways: "ClientRectangle.X", "ClientRectangle/X"
84 | ///
85 | ///
86 | ///
87 | /// //dotted notation:
88 | /// PropertyValue pt = PropertyValue.TraverseProperties(this.TopLevelControl, "ClientRectangle.X");
89 | /// //path notation:
90 | /// PropertyValue pt = PropertyValue.TraverseProperties(this.TopLevelControl, "ClientRectangle/X");
91 | /// //individual names:
92 | /// PropertyValue pt = PropertyValue.TraverseProperties(this.TopLevelControl, "ClientRectangle", "X");
93 | ///
94 | ///
95 | /// Any object to begin the traverse from
96 | /// The name of the properties or fields usually '.' delimited
97 | public static PropertyValue TraverseProperties(object instance, params string[] propertyNames)
98 | {
99 | PropertyValue prop = null;
100 |
101 | foreach (string propnames in Check.NotEmpty(propertyNames))
102 | {
103 | foreach (string name in Check.NotEmpty(propnames).Split('.', '/', '\\'))
104 | {
105 | prop = new PropertyValue(instance, Check.NotEmpty(name));
106 | instance = prop.Value;
107 | }
108 | }
109 |
110 | return Check.NotNull(prop);
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleCustomTypeTest.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using CSharpTest.Net.BPlusTree.Test.SampleTypes;
18 | using CSharpTest.Net.Collections;
19 | using CSharpTest.Net.Crypto;
20 | using CSharpTest.Net.Interfaces;
21 | using CSharpTest.Net.IO;
22 | using NUnit.Framework;
23 |
24 | namespace CSharpTest.Net.BPlusTree.Test
25 | {
26 | [TestFixture]
27 | public class SampleCustomTypeTest : TestDictionary, SampleCustomTypeTest.BTreeFactory, KeyInfo, DataValue>
28 | {
29 | protected TempFile TempFile;
30 | #region TestFixture SetUp/TearDown
31 | [TestFixtureSetUp]
32 | public virtual void Setup()
33 | {
34 | TempFile = new TempFile();
35 | }
36 |
37 | [TestFixtureTearDown]
38 | public virtual void Teardown()
39 | {
40 | TempFile.Dispose();
41 | }
42 | #endregion
43 |
44 | public class BTreeFactory : IFactory>
45 | {
46 | public BPlusTree Create()
47 | {
48 | BPlusTree.Options options =
49 | new BPlusTree.Options(new KeyInfoSerializer(), new DataValueSerializer(), new KeyInfoComparer())
50 | {
51 | MinimumChildNodes = 16,
52 | MaximumChildNodes = 24,
53 | MinimumValueNodes = 4,
54 | MaximumValueNodes = 12,
55 | };
56 |
57 | BPlusTree tree = new BPlusTree(options);
58 | tree.EnableCount();
59 | return tree;
60 | }
61 | }
62 |
63 | protected override KeyValuePair[] GetSample()
64 | {
65 | List> all = new List>();
66 |
67 | Random rand = new Random();
68 | byte[] data = new byte[255];
69 |
70 | for (int i = 0; i < 100; i++)
71 | {
72 | KeyInfo k1 = new KeyInfo();
73 | rand.NextBytes(data);
74 | all.Add(new KeyValuePair(k1, new DataValue(k1, data)));
75 | }
76 | return all.ToArray();
77 | }
78 |
79 | [Test]
80 | public void TestCommonConfiguration()
81 | {
82 | BPlusTree.Options options =
83 | new BPlusTree.Options(new KeyInfoSerializer(), new DataValueSerializer(), new KeyInfoComparer());
84 | options.CalcBTreeOrder(32, 300);//we can simply just guess close
85 | options.FileName = TempFile.TempPath;
86 | options.CreateFile = CreatePolicy.Always;//obviously this is just for testing
87 | Assert.AreEqual(FileVersion.Version1, options.FileVersion);
88 |
89 | Random rand = new Random();
90 | KeyInfo k1 = new KeyInfo(), k2 = new KeyInfo();
91 |
92 | using (BPlusTree tree = new BPlusTree(options))
93 | {
94 | byte[] data = new byte[255];
95 |
96 | rand.NextBytes(data);
97 | tree.Add(k1, new DataValue(k1, data));
98 |
99 | Assert.IsTrue(tree.ContainsKey(k1));
100 | Assert.IsFalse(tree.ContainsKey(k1.Next()));
101 | Assert.AreEqual(data, tree[k1].Bytes);
102 |
103 | rand.NextBytes(data);
104 | tree.Add(k2, new DataValue(k2, data));
105 |
106 | Assert.IsTrue(tree.ContainsKey(k2));
107 | Assert.IsFalse(tree.ContainsKey(k2.Next()));
108 | Assert.AreEqual(data, tree[k2].Bytes);
109 | }
110 | options.CreateFile = CreatePolicy.Never;
111 | using (BPlusTree tree = new BPlusTree(options))
112 | {
113 | Assert.IsTrue(tree.ContainsKey(k1));
114 | Assert.IsTrue(tree.ContainsKey(k2));
115 | }
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleTypes/DataValue.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using CSharpTest.Net.Crypto;
16 |
17 | namespace CSharpTest.Net.BPlusTree.Test.SampleTypes
18 | {
19 | public class DataValue
20 | {
21 | private Hash _hash;
22 | private byte[] _bytes;
23 | public DataValue(KeyInfo key, byte[] data)
24 | {
25 | Key = key;
26 | Bytes = data;
27 | }
28 |
29 | public readonly KeyInfo Key;
30 |
31 | public Hash Hash { get { return _hash; } }
32 | public byte[] Bytes
33 | {
34 | get { return (byte[])_bytes.Clone(); }
35 | set
36 | {
37 | _bytes = (byte[])value.Clone();
38 | _hash = Hash.SHA256(_bytes);
39 | }
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleTypes/DataValueSerializer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using CSharpTest.Net.Crypto;
16 | using CSharpTest.Net.Serialization;
17 | using NUnit.Framework;
18 |
19 | namespace CSharpTest.Net.BPlusTree.Test.SampleTypes
20 | {
21 | class DataValueSerializer : ISerializer
22 | {
23 | readonly KeyInfoSerializer _keySerializer = new KeyInfoSerializer();
24 |
25 | public DataValue ReadFrom(System.IO.Stream stream)
26 | {
27 | DataValue value = new DataValue(
28 | _keySerializer.ReadFrom(stream),
29 | PrimitiveSerializer.Bytes.ReadFrom(stream)
30 | );
31 |
32 | Hash cmpHash = Hash.FromString(PrimitiveSerializer.String.ReadFrom(stream));
33 | Assert.AreEqual(value.Hash, cmpHash);
34 | return value;
35 | }
36 |
37 | public void WriteTo(DataValue value, System.IO.Stream stream)
38 | {
39 | _keySerializer.WriteTo(value.Key, stream);
40 | PrimitiveSerializer.Bytes.WriteTo(value.Bytes, stream);
41 | PrimitiveSerializer.String.WriteTo(value.Hash.ToString(), stream);
42 | }
43 | }
44 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleTypes/KeyInfo.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.BPlusTree.Test.SampleTypes
18 | {
19 | public class KeyInfo
20 | {
21 | public readonly Guid UID;
22 | public readonly int Version;
23 |
24 | public KeyInfo() : this(Guid.NewGuid(), 1) { }
25 | public KeyInfo(Guid uid, int ver)
26 | {
27 | UID = uid;
28 | Version = ver;
29 | }
30 |
31 | public KeyInfo Next()
32 | {
33 | return new KeyInfo(UID, Version + 1);
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleTypes/KeyInfoComparer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Collections.Generic;
16 |
17 | namespace CSharpTest.Net.BPlusTree.Test.SampleTypes
18 | {
19 | class KeyInfoComparer : IComparer
20 | {
21 | public int Compare(KeyInfo x, KeyInfo y)
22 | {
23 | int result = x.UID.CompareTo(y.UID);
24 | if (result == 0)
25 | result = x.Version.CompareTo(y.Version);
26 | return result;
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/SampleTypes/KeyInfoSerializer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using CSharpTest.Net.Serialization;
16 |
17 | namespace CSharpTest.Net.BPlusTree.Test.SampleTypes
18 | {
19 | class KeyInfoSerializer : ISerializer
20 | {
21 | public KeyInfo ReadFrom(System.IO.Stream stream)
22 | {
23 | return new KeyInfo(
24 | PrimitiveSerializer.Guid.ReadFrom(stream),
25 | VariantNumberSerializer.Int32.ReadFrom(stream)
26 | );
27 | }
28 | public void WriteTo(KeyInfo value, System.IO.Stream stream)
29 | {
30 | PrimitiveSerializer.Guid.WriteTo(value.UID, stream);
31 | VariantNumberSerializer.Int32.WriteTo(value.Version, stream);
32 | }
33 | }
34 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/TestBPlusTreeOptions.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using CSharpTest.Net.IO;
18 | using CSharpTest.Net.Serialization;
19 | using NUnit.Framework;
20 | using CSharpTest.Net.Collections;
21 | using CSharpTest.Net.Synchronization;
22 |
23 | namespace CSharpTest.Net.BPlusTree.Test
24 | {
25 | [TestFixture]
26 | public class TestBPlusTreeOptions
27 | {
28 | [Test]
29 | public void TestICloneable()
30 | {
31 | ICloneable opt = new BPlusTree.Options(PrimitiveSerializer.Int32, PrimitiveSerializer.Int32)
32 | {
33 | CreateFile = CreatePolicy.IfNeeded,
34 | BTreeOrder = 4
35 | };
36 | BPlusTree.Options options = (BPlusTree.Options)opt.Clone();
37 |
38 | Assert.AreEqual(CreatePolicy.IfNeeded, options.CreateFile);
39 | Assert.AreEqual(4, options.MaximumChildNodes);
40 | Assert.AreEqual(4, options.MaximumValueNodes);
41 | }
42 |
43 | [Test]
44 | public void TestReadOnly()
45 | {
46 | using (TempFile file = new TempFile())
47 | {
48 | var opt = new BPlusTree.Options(PrimitiveSerializer.Int32, PrimitiveSerializer.Int32)
49 | {
50 | CreateFile = CreatePolicy.Always,
51 | FileName = file.TempPath,
52 | };
53 | using (BPlusTree tree = new BPlusTree(opt))
54 | {
55 | tree.Add(1, 2);
56 | tree.Add(3, 4);
57 | tree.Add(5, 6);
58 | }
59 |
60 | opt.CreateFile = CreatePolicy.Never;
61 | opt.ReadOnly = true;
62 | using (BPlusTree tree = new BPlusTree(opt))
63 | {
64 | Assert.AreEqual(tree[1], 2);
65 | Assert.AreEqual(tree[3], 4);
66 | Assert.AreEqual(tree[5], 6);
67 |
68 | try { tree[1] = 0; Assert.Fail(); }
69 | catch (InvalidOperationException) { }
70 |
71 | try { tree.Remove(1); Assert.Fail(); }
72 | catch (InvalidOperationException) { }
73 | }
74 | }
75 | }
76 |
77 | [Test]
78 | public void TestCloneWithCallLockV1()
79 | {
80 | var options = new BPlusTree.Options(PrimitiveSerializer.Int32, PrimitiveSerializer.Int32)
81 | {
82 | CreateFile = CreatePolicy.IfNeeded,
83 | BTreeOrder = 4
84 | };
85 | var copy = options.Clone();
86 |
87 | Assert.IsFalse(Object.ReferenceEquals(options, copy));
88 | Assert.IsTrue(Object.ReferenceEquals(options.CallLevelLock, copy.CallLevelLock));
89 |
90 | //If we get/set the lock prior to clone we will have the same lock instance.
91 | options.CallLevelLock = new SimpleReadWriteLocking();
92 | copy = options.Clone();
93 |
94 | Assert.IsFalse(Object.ReferenceEquals(options, copy));
95 | Assert.IsTrue(Object.ReferenceEquals(options.CallLevelLock, copy.CallLevelLock));
96 | }
97 |
98 | [Test]
99 | public void TestCloneWithCallLockV2()
100 | {
101 | var options = new BPlusTree.OptionsV2(PrimitiveSerializer.Int32, PrimitiveSerializer.Int32)
102 | {
103 | CreateFile = CreatePolicy.IfNeeded,
104 | BTreeOrder = 4
105 | };
106 | var copy = options.Clone();
107 |
108 | Assert.IsFalse(Object.ReferenceEquals(options, copy));
109 | Assert.IsFalse(Object.ReferenceEquals(options.CallLevelLock, copy.CallLevelLock));
110 |
111 | //If we get/set the lock prior to clone we will have the same lock instance.
112 | options.CallLevelLock = new SimpleReadWriteLocking();
113 | copy = options.Clone();
114 |
115 | Assert.IsFalse(Object.ReferenceEquals(options, copy));
116 | Assert.IsTrue(Object.ReferenceEquals(options.CallLevelLock, copy.CallLevelLock));
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/TestDictionary.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using CSharpTest.Net.Interfaces;
18 | using NUnit.Framework;
19 |
20 | namespace CSharpTest.Net.BPlusTree.Test
21 | {
22 | public abstract class TestDictionary : TestCollection>
23 | where TDictionary : IDictionary, IDisposable
24 | where TFactory : IFactory, new()
25 | {
26 | [Test]
27 | public void TestAddRemoveByKey()
28 | {
29 | KeyValuePair[] sample = GetSample();
30 |
31 | using (TDictionary test = Factory.Create())
32 | {
33 | foreach (KeyValuePair kv in sample)
34 | test.Add(kv.Key, kv.Value);
35 |
36 | foreach (KeyValuePair kv in sample)
37 | Assert.IsTrue(test.ContainsKey(kv.Key));
38 |
39 | TValue cmp;
40 | foreach (KeyValuePair kv in sample)
41 | Assert.IsTrue(test.TryGetValue(kv.Key, out cmp) && kv.Value.Equals(cmp));
42 |
43 | foreach (KeyValuePair kv in sample)
44 | Assert.IsTrue(test.Remove(kv.Key));
45 | }
46 | }
47 |
48 | [Test]
49 | public void TestKeys()
50 | {
51 | KeyValuePair[] sample = GetSample();
52 |
53 | using (TDictionary test = Factory.Create())
54 | {
55 | List keys = new List();
56 |
57 | foreach (KeyValuePair kv in sample)
58 | {
59 | test[kv.Key] = kv.Value;
60 | keys.Add(kv.Key);
61 | }
62 |
63 | List cmp = new List(test.Keys);
64 |
65 | Assert.AreEqual(keys.Count, cmp.Count);
66 | for (int i = 0; i < keys.Count; i++)
67 | Assert.IsTrue(test.ContainsKey(keys[i]));
68 | }
69 | }
70 |
71 | [Test]
72 | public void TestValues()
73 | {
74 | KeyValuePair[] sample = GetSample();
75 |
76 | using (TDictionary test = Factory.Create())
77 | {
78 | List values = new List();
79 |
80 | foreach (KeyValuePair kv in sample)
81 | {
82 | test[kv.Key] = kv.Value;
83 | values.Add(kv.Value);
84 | }
85 |
86 | List cmp = new List(test.Values);
87 | Assert.AreEqual(values.Count, cmp.Count);
88 | }
89 | }
90 | }
91 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/TestSimpleDictionary.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Collections.Generic;
16 | using CSharpTest.Net.Collections;
17 | using CSharpTest.Net.Interfaces;
18 | using CSharpTest.Net.Serialization;
19 | using CSharpTest.Net.Synchronization;
20 | using NUnit.Framework;
21 |
22 | namespace CSharpTest.Net.BPlusTree.Test
23 | {
24 | [TestFixture]
25 | public class TestSimpleDictionary : TestDictionary, TestSimpleDictionary.BTreeFactory, int, string>
26 | {
27 | public class BTreeFactory : IFactory>
28 | {
29 | public BPlusTree Create()
30 | {
31 | BPlusTree tree = new BPlusTree(
32 | new BPlusTree.Options(PrimitiveSerializer.Instance, PrimitiveSerializer.Instance)
33 | {
34 | BTreeOrder = 4,
35 | LockingFactory = new IgnoreLockFactory()
36 | }
37 | );
38 | tree.EnableCount();
39 | return tree;
40 | }
41 | }
42 |
43 | protected override KeyValuePair[] GetSample()
44 | {
45 | return new[]
46 | {
47 | new KeyValuePair(1, "1"),
48 | new KeyValuePair(3, "3"),
49 | new KeyValuePair(5, "5"),
50 | new KeyValuePair(7, "7"),
51 | new KeyValuePair(9, "9"),
52 | new KeyValuePair(11, "11"),
53 | new KeyValuePair(13, "13"),
54 | };
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/Threading/IWorkQueue.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.IO;
17 |
18 | namespace CSharpTest.Net.Threading
19 | {
20 | /// Provides an interface for a simple WorkQueue
21 | public interface IWorkQueue : IDisposable
22 | {
23 | /// Raised when a task fails to handle an error
24 | event ErrorEventHandler OnError;
25 | /// Waits for all queued tasks to complete and then exists all threads
26 | /// Returns true if all pending tasks were completed before the timeout expired.
27 | bool Complete(bool completePending, int timeout);
28 | /// Enqueues a task
29 | void Enqueue(T instance);
30 | }
31 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.BPlusTreeTest/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Bases/Disposable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using System.ComponentModel;
18 |
19 | namespace CSharpTest.Net.Bases
20 | {
21 | ///
22 | /// Wraps the IDisposable object interface for classes that desire to be sure of being called
23 | /// a single time for the dispose.
24 | ///
25 | public abstract class Disposable : IDisposable
26 | {
27 | private bool _isDisposed;
28 | private event EventHandler DisposedEvent;
29 |
30 | ///
31 | protected Disposable()
32 | {
33 | _isDisposed = false;
34 | }
35 |
36 | /// last-chance dispose
37 | ~Disposable()
38 | { try { OnDispose(false); } catch { } }
39 |
40 | /// disposes of the object if it has not already been disposed
41 | public void Dispose()
42 | {
43 | try { OnDispose(true); }
44 | finally { GC.SuppressFinalize(this); }
45 | }
46 |
47 | private void OnDispose(bool disposing)
48 | {
49 | try
50 | {
51 | if (!_isDisposed)
52 | {
53 | Dispose(disposing);
54 | if (DisposedEvent != null)
55 | DisposedEvent(this, EventArgs.Empty);
56 | }
57 | }
58 | finally
59 | {
60 | _isDisposed = true;
61 | DisposedEvent = null;
62 | }
63 | }
64 |
65 | /// Raised when the object is disposed
66 | public event EventHandler Disposed
67 | {
68 | add { Assert(); DisposedEvent += value; }
69 | remove { DisposedEvent -= value; }
70 | }
71 |
72 | /// Raises the ObjectDisposedException if this object has already been disposed
73 | protected virtual void Assert()
74 | {
75 | if (_isDisposed) throw new ObjectDisposedException(GetType().FullName);
76 | }
77 |
78 | /// Your implementation of the dispose method
79 | protected abstract void Dispose(bool disposing);
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Bases/Equatable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.Bases
19 | {
20 | /// Provides a base-class for non-reference equality objects
21 | [System.Diagnostics.DebuggerNonUserCode]
22 | public abstract class Equatable : IEquatable
23 | where T : Equatable
24 | {
25 | /// return a non-reference equality comparer for this class
26 | public static readonly EqualityComparer Comparer = new EqualityComparer();
27 |
28 | /// Extracts the correct hash code
29 | protected abstract int HashCode { get; }
30 |
31 | /// Returns true if the other object is equal to this one
32 | public abstract bool Equals(T other);
33 |
34 | /// Returns true if the other object is equal to this one
35 | public sealed override bool Equals(object obj)
36 | {
37 | return Comparer.Equals(this as T, obj as T);
38 | }
39 |
40 | /// Extracts the correct hash code
41 | public sealed override int GetHashCode()
42 | {
43 | return Comparer.GetHashCode(this as T);
44 | }
45 |
46 | /// Compares the two objects for non-reference equality
47 | public static bool Equals(T x, T y)
48 | {
49 | return Comparer.Equals(x, y);
50 | }
51 | /// Compares the two objects for non-reference equality
52 | public static int GetHashCode(T obj)
53 | {
54 | return Comparer.GetHashCode(obj);
55 | }
56 |
57 | /// Compares the two objects for non-reference equality
58 | public static bool operator ==(Equatable x, Equatable y)
59 | {
60 | return Comparer.Equals(x as T, y as T);
61 | }
62 | /// Compares the two objects for non-reference equality
63 | public static bool operator !=(Equatable x, Equatable y)
64 | {
65 | return !Comparer.Equals(x as T, y as T);
66 | }
67 |
68 | /// Implements the equality comparer
69 | [System.Diagnostics.DebuggerNonUserCode]
70 | public sealed class EqualityComparer : EqualityComparer, IEqualityComparer
71 | {
72 | /// Compares the two objects for non-reference equality
73 | public override bool Equals(T x, T y)
74 | {
75 | if (((object)x) == null) return ((object)y) == null;
76 | if (((object)y) == null) return false;
77 | return x.Equals(y);
78 | }
79 | /// Extracts the correct hash code
80 | public override int GetHashCode(T obj)
81 | {
82 | return ((object)obj) == null ? 0 : obj.HashCode;
83 | }
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/CmdTool.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/DisposingList.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.Collections
19 | {
20 | ///
21 | /// Disposes of each element in the collection when the collection is disposed.
22 | ///
23 | public class DisposingList : DisposingList
24 | {
25 | ///
26 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
27 | /// that is empty and has the default initial capacity.
28 | ///
29 | public DisposingList() : base() { }
30 | ///
31 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
32 | /// that contains elements copied from the specified collection and has sufficient
33 | /// capacity to accommodate the number of elements copied.
34 | ///
35 | public DisposingList(IEnumerable collection) : base(collection) { }
36 | ///
37 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
38 | /// that is empty and has the specified initial capacity.
39 | ///
40 | public DisposingList(int capacity) : base(capacity) { }
41 | }
42 |
43 | ///
44 | /// Disposes of each element in the collection when the collection is disposed.
45 | ///
46 | public class DisposingList : List, IDisposable
47 | where T : IDisposable
48 | {
49 | ///
50 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
51 | /// that is empty and has the default initial capacity.
52 | ///
53 | public DisposingList() : base() { }
54 | ///
55 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
56 | /// that contains elements copied from the specified collection and has sufficient
57 | /// capacity to accommodate the number of elements copied.
58 | ///
59 | public DisposingList(IEnumerable collection) : base(collection) { }
60 | ///
61 | /// Initializes a new instance of the System.Collections.Generic.List>T> class
62 | /// that is empty and has the specified initial capacity.
63 | ///
64 | public DisposingList(int capacity) : base(capacity) { }
65 |
66 | ///
67 | /// Disposes of each element in the collection when the collection is disposed.
68 | ///
69 | public void Dispose()
70 | {
71 | for (int i = base.Count - 1; i >= 0; i--)
72 | {
73 | T item = base[i];
74 | base.RemoveAt(i);
75 |
76 | if (item != null)
77 | item.Dispose();
78 | }
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/Element.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Diagnostics;
18 |
19 | namespace CSharpTest.Net.Collections
20 | {
21 | partial class BPlusTree
22 | {
23 | [DebuggerDisplay("{Key} = {_child}")]
24 | struct Element
25 | {
26 | public readonly TKey Key;
27 | private readonly object _child;
28 |
29 | public Element(TKey k) { Key = k; _child = null; }
30 | public Element(TKey k, NodeHandle ch) { Key = k; _child = ch; }
31 | public Element(TKey k, TValue value) { Key = k; _child = value; }
32 | public Element(TKey k, Element value) { Key = k; _child = value._child; }
33 |
34 | public bool IsNode { get { return _child is NodeHandle; } }
35 | public bool IsValue { get { return !(_child is NodeHandle); } } // Fix for null child value
36 | public bool IsEmpty { get { return ReferenceEquals(null, _child); } }
37 | public NodeHandle ChildNode { get { return (NodeHandle)_child; } }
38 | public TValue Payload { get { return (TValue)_child; } }
39 |
40 | public KeyValuePair ToKeyValuePair()
41 | {
42 | return new KeyValuePair(Key, Payload);
43 | }
44 | }
45 |
46 | class ElementComparer : IComparer
47 | {
48 | private readonly IComparer _keyCompare;
49 |
50 | public ElementComparer(IComparer keyCompare)
51 | {
52 | _keyCompare = keyCompare;
53 | }
54 |
55 | public int Compare(Element x, Element y)
56 | {
57 | return _keyCompare.Compare(x.Key, y.Key);
58 | }
59 | }
60 | }
61 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/HashUtilities.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Collections
18 | {
19 | internal class HashUtilities
20 | {
21 | private static readonly int[] PrimeNumbers =
22 | new[]
23 | {
24 | 17, 37, 67, 131, 257, 521, // ROK - Added smaller primes
25 | 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
26 | 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
27 | 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687,
28 | 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369
29 | };
30 |
31 | internal static int SelectPrimeNumber(int hashSize)
32 | {
33 | int offset = Array.BinarySearch(PrimeNumbers, hashSize);
34 | if (offset < 0)
35 | offset = ~offset;
36 | return PrimeNumbers[Math.Min(offset, PrimeNumbers.Length - 1)];
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/IDictionaryEx.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.Collections
19 | {
20 | ///
21 | /// Extends the IDictionary interface to encompass the TryXxxx operations
22 | ///
23 | public interface IDictionaryEx : IDictionary, IDisposable
24 | {
25 | ///
26 | /// Adds a key/value pair to the if the key does not already exist.
27 | ///
28 | /// The key of the element to add.
29 | /// The value to be added, if the key does not already exist.
30 | /// The is read-only.
31 | TValue GetOrAdd(TKey key, TValue value);
32 |
33 | ///
34 | /// Adds an element with the provided key and value to the .
35 | ///
36 | /// The object to use as the key of the element to add.
37 | /// The object to use as the value of the element to add.
38 | /// The is read-only.
39 | bool TryAdd(TKey key, TValue value);
40 |
41 | ///
42 | /// Updates an element with the provided key to the value if it exists.
43 | ///
44 | /// Returns true if the key provided was found and updated to the value.
45 | /// The object to use as the key of the element to update.
46 | /// The new value for the key if found.
47 | /// The is read-only.
48 | bool TryUpdate(TKey key, TValue value);
49 |
50 | ///
51 | /// Updates an element with the provided key to the value if it exists.
52 | ///
53 | /// Returns true if the key provided was found and updated to the value.
54 | /// The object to use as the key of the element to update.
55 | /// The new value for the key if found.
56 | /// The value that is compared to the value of the element with key.
57 | /// The is read-only.
58 | bool TryUpdate(TKey key, TValue value, TValue comparisonValue);
59 |
60 | ///
61 | /// Removes the element with the specified key from the .
62 | ///
63 | ///
64 | /// true if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original .
65 | ///
66 | /// The key of the element to remove.
67 | /// The value that was removed.
68 | /// The is read-only.
69 | bool TryRemove(TKey key, out TValue value);
70 | }
71 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/Interfaces.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using CSharpTest.Net.Serialization;
17 |
18 | namespace CSharpTest.Net.Collections
19 | {
20 | /// Identifies a class as a reference to a node instance
21 | public interface IStorageHandle : IEquatable
22 | { }
23 |
24 | /// Represents a persistance mechanic for node data
25 | public interface INodeStorage : ISerializer, IDisposable
26 | {
27 | /// Returns an immutable handle to the root node, sets isNew to true if no data exists
28 | IStorageHandle OpenRoot(out bool isNew);
29 |
30 | /// Destroys the entire contents of the storage system except for the root handle which remains valid
31 | void Reset();
32 |
33 | /// Retrieves a single node from storage
34 | bool TryGetNode(IStorageHandle handle, out TNode node, ISerializer serializer);
35 |
36 | /// Creates a node handle that will represent a new node instance
37 | IStorageHandle Create();
38 |
39 | /// Destroys the node that was formally stored by the specified handle
40 | void Destroy(IStorageHandle handle);
41 |
42 | /// Updates the node of the specified handle with the instance given
43 | void Update(IStorageHandle handle, ISerializer serializer, TNode node);
44 | }
45 |
46 | /// An optional interface that allows storage provides to persist the record count
47 | public interface INodeStoreWithCount : INodeStorage, Interfaces.ITransactable
48 | {
49 | ///
50 | /// Used to retrieve the current record count after opening a store, -1 indicates an invalid entry.
51 | /// Prior to Commit() the count will be set to the actual record count.
52 | ///
53 | int Count { get; set; }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/KeyValueComparer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Collections.Generic;
16 |
17 | namespace CSharpTest.Net.Collections
18 | {
19 | ///
20 | /// Represents a key-value comparison
21 | ///
22 | public class KeyValueComparer : IComparer>
23 | {
24 | private readonly IComparer _keyComparer;
25 |
26 | private static KeyValueComparer _defaultInstance;
27 | ///
28 | /// Represents a key-value comparison using the default comparer for type TKey
29 | ///
30 | public static KeyValueComparer Default
31 | {
32 | get
33 | {
34 | return _defaultInstance ??
35 | (_defaultInstance = new KeyValueComparer(Comparer.Default));
36 | }
37 | }
38 |
39 | ///
40 | /// Returns the comparer being used by this instance
41 | ///
42 | public IComparer Comparer { get { return _keyComparer; } }
43 |
44 | ///
45 | /// Creates a key-value comparison using the default comparer for type TKey
46 | ///
47 | public KeyValueComparer() : this(Comparer.Default) { }
48 |
49 | ///
50 | /// Creates a key-value comparison with the specified comparer
51 | ///
52 | public KeyValueComparer(IComparer keyComparer)
53 | {
54 | _keyComparer = Check.NotNull(keyComparer);
55 | }
56 |
57 | ///
58 | /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
59 | ///
60 | public int Compare(KeyValuePair x, KeyValuePair y)
61 | {
62 | return _keyComparer.Compare(x.Key, y.Key);
63 | }
64 | }
65 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/NodeCache.Full.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using CSharpTest.Net.Synchronization;
16 |
17 | namespace CSharpTest.Net.Collections
18 | {
19 | partial class BPlusTree
20 | {
21 | /// performs a perfect cache of the entire tree
22 | sealed class NodeCacheFull : NodeCacheBase
23 | {
24 | NodeHandle _root;
25 | public NodeCacheFull(BPlusTreeOptions options)
26 | : base(options)
27 | {}
28 |
29 | protected override void LoadStorage()
30 | {
31 | bool isNew;
32 | _root = new NodeHandle(Storage.OpenRoot(out isNew));
33 | _root.SetCacheEntry(new NodeWithLock(null, LockFactory.Create()));
34 | if (isNew)
35 | CreateRoot(_root);
36 |
37 | Node rootNode;
38 | if (Storage.TryGetNode(_root.StoreHandle, out rootNode, NodeSerializer))
39 | _root.SetCacheEntry(new NodeWithLock(rootNode, LockFactory.Create()));
40 |
41 | Assert(rootNode != null, "Unable to load storage root.");
42 | }
43 |
44 | protected override NodeHandle RootHandle
45 | {
46 | get { return _root; }
47 | }
48 |
49 | public override void ResetCache()
50 | {
51 | NodeWithLock nlck;
52 | if (_root.TryGetCache(out nlck))
53 | nlck.Node = null;
54 | }
55 |
56 | public override void UpdateNode(NodePin node)
57 | {
58 | if (!node.IsDeleted)
59 | {
60 | NodeWithLock nlck;
61 | if (!node.Handle.TryGetCache(out nlck))
62 | throw new AssertionFailedException("Unable to retrieve handle cache.");
63 | nlck.Node = node.Ptr;
64 | }
65 | }
66 |
67 | public override ILockStrategy CreateLock(NodeHandle handle, out object refobj)
68 | {
69 | NodeWithLock nlck = new NodeWithLock(null, LockFactory.Create());
70 | handle.SetCacheEntry(nlck);
71 | refobj = nlck;
72 | bool acquired = nlck.Lock.TryWrite(base.Options.LockTimeout);
73 | DeadlockException.Assert(acquired);
74 | return nlck.Lock;
75 | }
76 |
77 | protected override NodePin Lock(NodePin parent, LockType ltype, NodeHandle child)
78 | {
79 | NodeWithLock nlck;
80 | if (!child.TryGetCache(out nlck))
81 | child.SetCacheEntry(nlck = new NodeWithLock(null, LockFactory.Create()));
82 |
83 | bool acquired;
84 | if(ltype == LockType.Read)
85 | acquired = nlck.Lock.TryRead(base.Options.LockTimeout);
86 | else
87 | acquired = nlck.Lock.TryWrite(base.Options.LockTimeout);
88 | DeadlockException.Assert(acquired);
89 | try
90 | {
91 | if (nlck.Node == null)
92 | {
93 | using (new SafeLock(nlck, base.Options.LockTimeout))
94 | Storage.TryGetNode(child.StoreHandle, out nlck.Node, NodeSerializer);
95 | }
96 |
97 | Assert(nlck.Node != null);
98 | return new NodePin(child, nlck.Lock, ltype, ltype, nlck, nlck.Node, null);
99 | }
100 | catch
101 | {
102 | if (ltype == LockType.Read)
103 | nlck.Lock.ReleaseRead();
104 | else
105 | nlck.Lock.ReleaseWrite();
106 | throw;
107 | }
108 | }
109 |
110 | class NodeWithLock
111 | {
112 | public readonly ILockStrategy Lock;
113 | public Node Node;
114 |
115 | public NodeWithLock(Node node, ILockStrategy lck)
116 | {
117 | Node = node;
118 | Lock = lck;
119 | }
120 | }
121 | }
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/NodeHandle.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Diagnostics;
16 | using CSharpTest.Net.Bases;
17 | using CSharpTest.Net.Serialization;
18 |
19 | namespace CSharpTest.Net.Collections
20 | {
21 | partial class BPlusTree
22 | {
23 | [DebuggerDisplay("Handle({_storeHandle})")]
24 | class NodeHandle : Equatable
25 | {
26 | private readonly IStorageHandle _storeHandle;
27 | private object _cacheEntry;
28 |
29 | public NodeHandle(IStorageHandle storeHandle)
30 | {
31 | _storeHandle = storeHandle;
32 | }
33 |
34 | public IStorageHandle StoreHandle { get { return _storeHandle; } }
35 |
36 | public bool TryGetCache(out T cacheEntry) where T : class
37 | {
38 | cacheEntry = _cacheEntry as T;
39 | return cacheEntry != null;
40 | }
41 |
42 | public void SetCacheEntry(object cacheEntry)
43 | { _cacheEntry = cacheEntry; }
44 |
45 | protected override int HashCode { get { return _storeHandle.GetHashCode(); } }
46 | public override bool Equals(NodeHandle other) { return _storeHandle.Equals(other._storeHandle); }
47 | }
48 |
49 | class NodeHandleSerializer : ISerializer, ISerializer
50 | {
51 | private readonly ISerializer _handleSerializer;
52 |
53 | public NodeHandleSerializer(ISerializer handleSerializer)
54 | {
55 | _handleSerializer = handleSerializer;
56 | }
57 |
58 | public void WriteTo(NodeHandle value, System.IO.Stream stream)
59 | { _handleSerializer.WriteTo(value.StoreHandle, stream); }
60 |
61 | public NodeHandle ReadFrom(System.IO.Stream stream)
62 | { return new NodeHandle(_handleSerializer.ReadFrom(stream)); }
63 |
64 | public void WriteTo(IStorageHandle value, System.IO.Stream stream)
65 | { _handleSerializer.WriteTo(value, stream); }
66 |
67 | IStorageHandle ISerializer.ReadFrom(System.IO.Stream stream)
68 | { return _handleSerializer.ReadFrom(stream); }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Collections/OrderedKeyValuePairs.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Collections.Generic;
16 | using CSharpTest.Net.Serialization;
17 |
18 | namespace CSharpTest.Net.Collections
19 | {
20 | ///
21 | /// Speicalizes the OrderedEnumeration of T to use key/value pairs with a key comparer.
22 | ///
23 | public class OrderedKeyValuePairs : OrderedEnumeration>
24 | {
25 | /// Constructs an ordered set of KeyValuePair structs
26 | public OrderedKeyValuePairs(IEnumerable> unordered)
27 | : base(KeyValueComparer.Default, unordered)
28 | {
29 | }
30 | /// Constructs an ordered set of KeyValuePair structs
31 | public OrderedKeyValuePairs(IComparer comparer, IEnumerable> unordered)
32 | : base(new KeyValueComparer(comparer), unordered)
33 | {
34 | }
35 | /// Constructs an ordered set of KeyValuePair structs
36 | public OrderedKeyValuePairs(IComparer comparer, IEnumerable> unordered,
37 | ISerializer> serializer)
38 | : base(new KeyValueComparer(comparer), unordered, serializer)
39 | {
40 | }
41 | /// Constructs an ordered set of KeyValuePair structs
42 | public OrderedKeyValuePairs(IComparer comparer, IEnumerable> unordered,
43 | ISerializer> serializer, int memoryLimit)
44 | : base(new KeyValueComparer(comparer), unordered, serializer, memoryLimit)
45 | {
46 | }
47 | /// Constructs an ordered set of KeyValuePair structs
48 | public OrderedKeyValuePairs(IComparer comparer, IEnumerable> unordered,
49 | ISerializer keySerializer, ISerializer valueSerializer)
50 | : base(
51 | new KeyValueComparer(comparer), unordered,
52 | new KeyValueSerializer(keySerializer, valueSerializer))
53 | {
54 | }
55 | /// Constructs an ordered set of KeyValuePair structs
56 | public OrderedKeyValuePairs(IComparer comparer, IEnumerable> unordered,
57 | ISerializer keySerializer, ISerializer valueSerializer,
58 | int memoryLimit)
59 | : base(
60 | new KeyValueComparer(comparer), unordered,
61 | new KeyValueSerializer(keySerializer, valueSerializer), memoryLimit)
62 | {
63 | }
64 | ///
65 | /// Merges n-number of ordered enumerations based on the comparer provided.
66 | ///
67 | public static IEnumerable> Merge(IComparer comparer, params IEnumerable>[] enums)
68 | {
69 | return Merge(new KeyValueComparer(comparer), enums);
70 | }
71 | ///
72 | /// Merges n-number of ordered enumerations based on the comparer provided.
73 | ///
74 | public static IEnumerable> Merge(IComparer comparer, DuplicateHandling duplicateHandling, params IEnumerable>[] enums)
75 | {
76 | KeyValueComparer kvcompare = new KeyValueComparer(comparer);
77 | return WithDuplicateHandling(Merge(kvcompare, enums), kvcompare, duplicateHandling);
78 | }
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Exceptions.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Diagnostics;
17 | using System.Runtime.CompilerServices;
18 | using System.Runtime.Serialization;
19 |
20 | namespace CSharpTest.Net
21 | {
22 | /// The base class for BPlutTree runtime assertions
23 | [System.SerializableAttribute()]
24 | [global::System.Diagnostics.DebuggerStepThroughAttribute()]
25 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
26 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
27 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("CSharpTest.Net.Generators", "1.11.225.410")]
28 | public abstract class BaseAssertionException : ApplicationException
29 | {
30 | /// The base class for BPlutTree runtime assertions
31 | protected BaseAssertionException(SerializationInfo info, StreamingContext context)
32 | : base(info, context)
33 | { }
34 |
35 | /// The base class for BPlutTree runtime assertions
36 | protected BaseAssertionException(string text)
37 | : base(AssertionText(text))
38 | { }
39 |
40 | /// The base class for BPlutTree runtime assertions
41 | protected BaseAssertionException(string text, Exception innerException)
42 | : base(AssertionText(text), innerException)
43 | { }
44 |
45 | [DebuggerNonUserCode, MethodImpl(MethodImplOptions.NoInlining)]
46 | private static string AssertionText(string message)
47 | {
48 | if (String.IsNullOrEmpty(message))
49 | message = Resources.ExceptionStrings.AssertionFailedException;
50 | #if DEBUG
51 | return String.Format("{0}\r\n at {0}", new StackFrame(2, true));
52 | #else
53 | return message;
54 | #endif
55 | }
56 | }
57 |
58 | partial class AssertionFailedException
59 | {
60 | ///
61 | /// if(condition == false) throws A runtime assertion failed: {0}
62 | ///
63 | public static void Assert(bool condition, string format, params object[] args)
64 | {
65 | if (!condition)
66 | {
67 | if (args != null && args.Length > 0)
68 | {
69 | try { format = String.Format(format, args); }
70 | catch (Exception e)
71 | { format = String.Format("{0} format error: {1}", format, e.Message); }
72 | }
73 | throw new AssertionFailedException(format ?? Resources.ExceptionStrings.AssertionFailedException);
74 | }
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/IO/BinaryComparer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.IO
19 | {
20 | ///
21 | /// Dictionary comparer for comparing arrays of bytes by value equality
22 | ///
23 | public sealed class BinaryComparer : IEqualityComparer, IComparer
24 | {
25 | /// returns true if both arrays contain the exact same set of bytes.
26 | public static bool Equals(byte[] ar1, byte[] ar2)
27 | { return 0 == Compare(ar1, ar2); }
28 |
29 | /// Compares the contents of the byte arrays and returns the result.
30 | public static int Compare(byte[] ar1, byte[] ar2)
31 | {
32 | if (ar1 == null) return ar2 == null ? 0 : -1;
33 | if (ar2 == null) return 1;
34 |
35 | int result = 0;
36 | int i = 0, stop = Math.Min(ar1.Length, ar2.Length);
37 |
38 | for (; 0 == result && i < stop; i++)
39 | result = ar1[i].CompareTo(ar2[i]);
40 |
41 | if (result != 0)
42 | return result;
43 | if (i == ar1.Length)
44 | return i == ar2.Length ? 0 : -1;
45 | return 1;
46 | }
47 |
48 | /// Returns a hash code the instance of the object
49 | public static int GetHashCode(byte[] bytes)
50 | {
51 | if(bytes == null) return 0;
52 | return new IO.Crc32(bytes).Value;
53 | }
54 |
55 | /// Compares the contents of the byte arrays and returns the result.
56 | int IComparer.Compare(byte[] x, byte[] y)
57 | {
58 | return BinaryComparer.Compare(x, y);
59 | }
60 |
61 | /// Returns true if the two objects are the same instance
62 | bool IEqualityComparer.Equals(byte[] x, byte[] y)
63 | {
64 | return 0 == BinaryComparer.Compare(x, y);
65 | }
66 |
67 | /// Returns a hash code the instance of the object
68 | int IEqualityComparer.GetHashCode(byte[] bytes)
69 | {
70 | return BinaryComparer.GetHashCode(bytes);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/IO/FileStreamFactory.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.IO;
16 | using CSharpTest.Net.Interfaces;
17 |
18 | namespace CSharpTest.Net.IO
19 | {
20 | ///
21 | /// Provides a default implementation of an IFactory for creating streams on a single file.
22 | ///
23 | public class FileStreamFactory : IFactory
24 | {
25 | const int DefaultBuffer = 4096;
26 | readonly string _filename;
27 | readonly FileMode _mode;
28 | readonly FileAccess _access;
29 | readonly FileShare _share;
30 | readonly int _bufferSize;
31 | readonly FileOptions _options;
32 |
33 | /// Creates an IFactory for creating streams on a single file
34 | public FileStreamFactory(string filename, FileMode mode)
35 | : this(filename, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, DefaultBuffer, FileOptions.None)
36 | { }
37 | /// Creates an IFactory for creating streams on a single file
38 | public FileStreamFactory(string filename, FileMode mode, FileAccess access)
39 | : this(filename, mode, access, access == FileAccess.Read ? FileShare.Read : FileShare.None, DefaultBuffer, FileOptions.None)
40 | { }
41 | /// Creates an IFactory for creating streams on a single file
42 | public FileStreamFactory(string filename, FileMode mode, FileAccess access, FileShare share)
43 | : this(filename, mode, access, share, DefaultBuffer, FileOptions.None)
44 | { }
45 | /// Creates an IFactory for creating streams on a single file
46 | public FileStreamFactory(string filename, FileMode mode, FileAccess access, FileShare share, int bufferSize)
47 | : this(filename, mode, access, share, bufferSize, FileOptions.None)
48 | { }
49 | /// Creates an IFactory for creating streams on a single file
50 | public FileStreamFactory(string filename, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
51 | {
52 | _filename = Check.NotEmpty(filename);
53 | _mode = mode;
54 | _access = access;
55 | _share = share;
56 | _bufferSize = bufferSize;
57 | _options = options;
58 | }
59 |
60 | /// The FileName that this factory produces streams for
61 | public string FileName { get { return _filename; } }
62 |
63 | ///
64 | /// Creates the file stream
65 | ///
66 | public Stream Create()
67 | {
68 | return new FileStream(_filename, _mode, _access, _share, _bufferSize, _options);
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/IO/IOStream.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using System.IO;
18 | using System.Text;
19 | using System.IO.Compression;
20 |
21 | namespace CSharpTest.Net.IO
22 | {
23 | ///
24 | /// A collection of Stream helpers
25 | ///
26 | public static class IOStream
27 | {
28 | /// Reads all of the bytes from the input stream, input stream will be disposed
29 | public static byte[] ReadAllBytes(Stream io)
30 | {
31 | using (io)
32 | using (MemoryStream ms = new MemoryStream())
33 | {
34 | CopyStream(io, ms);
35 | return ms.ToArray();
36 | }
37 | }
38 | /// Reads all of the bytes from the input stream, input stream will be disposed
39 | public static string ReadAllText(Stream io, Encoding encoding)
40 | {
41 | using (io)
42 | return encoding.GetString(ReadAllBytes(io));
43 | }
44 | /// Reads a the number of bytes specified or throws IOException
45 | public static void Read(Stream io, byte[] bytes)
46 | { Read(io, bytes, bytes.Length); }
47 | /// Reads a the number of bytes specified or throws IOException
48 | public static byte[] Read(Stream io, int nBytes)
49 | {
50 | byte[] bytes = new byte[nBytes];
51 | Read(io, bytes, nBytes);
52 | return bytes;
53 | }
54 | /// Reads a the number of bytes specified or throws IOException
55 | public static void Read(Stream io, byte[] bytes, int length)
56 | {
57 | if (length != ReadChunk(io, bytes, length))
58 | throw new IOException(Resources.IOStreamFailedToRead);
59 | }
60 |
61 | /// Attempts to read the number of bytes specified and returns the actual count
62 | public static int ReadChunk(Stream io, byte[] bytes, int length)
63 | { return ReadChunk(io, bytes, 0, length); }
64 |
65 | /// Attempts to read the number of bytes specified and returns the actual count
66 | public static int ReadChunk(Stream io, byte[] bytes, int offset, int length)
67 | {
68 | int bytesRead = 0;
69 | int len = 0;
70 | while (length > bytesRead && 0 != (len = io.Read(bytes, bytesRead, length - bytesRead)))
71 | bytesRead += len;
72 | return bytesRead;
73 | }
74 |
75 | /// Copy the entire input stream to the provided output stream, input stream will be disposed
76 | /// The number of bytes copied
77 | public static long CopyStream(Stream input, Stream output)
78 | {
79 | using (input)
80 | return CopyStream(input, output, long.MaxValue);
81 | }
82 | /// Copy the specified number of bytes from the input stream to the provided output stream
83 | /// The number of bytes copied
84 | public static long CopyStream(Stream input, Stream output, long stopAfter)
85 | {
86 | byte[] bytes = new byte[ushort.MaxValue];
87 | long bytesRead = 0;
88 | int len = 0;
89 | while (0 != (len = input.Read(bytes, 0, Math.Min(bytes.Length, (int)Math.Min(int.MaxValue, stopAfter - bytesRead)))))
90 | {
91 | output.Write(bytes, 0, len);
92 | bytesRead = bytesRead + len;
93 | }
94 | output.Flush();
95 | return bytesRead;
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Interfaces/DefaultFactories.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Interfaces
18 | {
19 | ///
20 | /// A static singleton and factory that uses a globally common instance.
21 | ///
22 | public static class Singleton where T : new()
23 | {
24 | ///
25 | /// Returns the singleton instance of T
26 | ///
27 | public static T Instance
28 | {
29 | get
30 | {
31 | if (Lazy._error != null)
32 | throw new ApplicationException(Resources.FailedToConstructSingleton(typeof(T)), Lazy._error);
33 | return Lazy._instance;
34 | }
35 | }
36 |
37 | private class Lazy
38 | {
39 | static Lazy()
40 | {
41 | try
42 | {
43 | _error = null;
44 | _instance = new T();
45 | }
46 | catch (Exception error)
47 | {
48 | _error = error;
49 | }
50 | }
51 |
52 | public static readonly T _instance;
53 | public static readonly Exception _error;
54 | }
55 |
56 | ///
57 | /// Returns a factory that returns the singleton instance
58 | ///
59 | public static IFactory Factory { get { return FactoryImpl._instance; } }
60 |
61 | private class FactoryImpl : IFactory
62 | {
63 | T IFactory.Create() { return Instance; }
64 | static FactoryImpl() { _instance = new FactoryImpl(); }
65 | public static readonly FactoryImpl _instance;
66 | }
67 | }
68 |
69 | ///
70 | /// A factory that creates a new instance of an object each time Create() is called.
71 | ///
72 | public class NewFactory : IFactory
73 | where T : new()
74 | {
75 | /// Returns a new instance of T
76 | public T Create()
77 | {
78 | return new T();
79 | }
80 | }
81 |
82 | ///
83 | /// A delegate that takes no arguemnts and returns a single value
84 | ///
85 | public delegate T FactoryMethod();
86 |
87 | ///
88 | /// A factory that creates a new instance of an object each time Create() is called.
89 | ///
90 | public class DelegateFactory : IFactory
91 | {
92 | private FactoryMethod _method;
93 |
94 | /// A factory that delegates instance creation
95 | public DelegateFactory(FactoryMethod method)
96 | {
97 | _method = method;
98 | }
99 |
100 | /// Returns an instance of T
101 | public T Create()
102 | {
103 | return _method();
104 | }
105 | }
106 |
107 | ///
108 | /// A factory that always returns the same instance of an object each time Create() is called.
109 | ///
110 | public class InstanceFactory : IFactory
111 | {
112 | private readonly T _instance;
113 |
114 | /// Provide the instance of T
115 | public InstanceFactory(T instance)
116 | {
117 | _instance = instance;
118 | }
119 |
120 | /// Returns the instance of T given to the constructor
121 | public T Create()
122 | {
123 | return _instance;
124 | }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Interfaces/ICloneable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 |
18 | namespace CSharpTest.Net.Interfaces
19 | {
20 | ///
21 | /// Provides a strongly typed shallow copy of the current object
22 | ///
23 | public interface ICloneable : ICloneable
24 | where T : ICloneable
25 | {
26 | ///
27 | /// Returns a shallow clone of this object.
28 | ///
29 | new T Clone();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Interfaces/IFactory.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | namespace CSharpTest.Net.Interfaces
16 | {
17 | /// Generic factory for instances of type T
18 | public interface IFactory
19 | {
20 | /// Creates an instance of an object assignable to type T
21 | T Create();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Interfaces/ITransactable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Interfaces
18 | {
19 | /// Supplies a common interface to transaction based objects
20 | public interface ITransactable : IDisposable
21 | {
22 | /// Completes the operation
23 | void Commit();
24 | /// Aborts the operation and reverts pending changes
25 | void Rollback();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2009-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Reflection;
16 | using System.Runtime.InteropServices;
17 |
18 | [assembly: AssemblyTitle("CSharpTest.Net.Collections.dll")]
19 | [assembly: AssemblyDescription("Fully managed B+ Tree implementation for local data storage.")]
20 | [assembly: AssemblyProduct("http://CSharpTest.Net/Projects")]
21 | [assembly: AssemblyConfiguration("Debug")]
22 |
23 | [assembly: AssemblyCompany("Roger Knapp")]
24 | [assembly: AssemblyCopyright("Copyright 2009 by Roger Knapp, Licensed under the Apache License, Version 2.0")]
25 |
26 | [assembly: AssemblyVersion("1.0.0.0")]
27 | [assembly: AssemblyFileVersion("1.0.0.0")]
28 |
29 | [assembly: ObfuscateAssembly(false)]
30 | [assembly: ComVisibleAttribute(false)]
31 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Serialization/ISerializer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.IO;
16 | using CSharpTest.Net.IO;
17 |
18 | namespace CSharpTest.Net.Serialization
19 | {
20 | /// Provides serialization for a type
21 | public interface ISerializer
22 | {
23 | /// Writes the object to the stream
24 | void WriteTo(T value, Stream stream);
25 | /// Reads the object from a stream
26 | T ReadFrom(Stream stream);
27 | }
28 |
29 | ///
30 | /// Returns all bytes in the stream, or writes all bytes to the stream
31 | ///
32 | public class BytesSerializer : ISerializer
33 | {
34 | /// Gets a singleton of the BytesSerializer class
35 | public static readonly ISerializer RawBytes = new BytesSerializer();
36 |
37 | void ISerializer.WriteTo(byte[] value, Stream stream)
38 | { stream.Write(value, 0, value.Length); }
39 |
40 | byte[] ISerializer.ReadFrom(Stream stream)
41 | { return IOStream.ReadAllBytes(stream); }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Serialization/KeyValueSerializer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2012-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.Collections.Generic;
16 |
17 | namespace CSharpTest.Net.Serialization
18 | {
19 | ///
20 | /// Implements ISerializer of KeyValuePair<TKey, TValue>
21 | ///
22 | public sealed class KeyValueSerializer : ISerializer>
23 | {
24 | private readonly ISerializer _keySerializer;
25 | private readonly ISerializer _valueSerializer;
26 |
27 | ///
28 | /// Provide the key/value serializers to use.
29 | ///
30 | public KeyValueSerializer(ISerializer keySerializer, ISerializer valueSerializer)
31 | {
32 | _keySerializer = keySerializer;
33 | _valueSerializer = valueSerializer;
34 | }
35 |
36 | /// Writes the object to the stream
37 | public void WriteTo(KeyValuePair value, System.IO.Stream stream)
38 | {
39 | _keySerializer.WriteTo(value.Key, stream);
40 | _valueSerializer.WriteTo(value.Value, stream);
41 | }
42 |
43 | /// Reads the object from a stream
44 | public KeyValuePair ReadFrom(System.IO.Stream stream)
45 | {
46 | return new KeyValuePair(
47 | _keySerializer.ReadFrom(stream),
48 | _valueSerializer.ReadFrom(stream)
49 | );
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Serialization/VariantNumberSerializer.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System.IO;
16 |
17 | namespace CSharpTest.Net.Serialization
18 | {
19 | ///
20 | /// Provides numeric serializers for packed int/long values.
21 | ///
22 | public class VariantNumberSerializer :
23 | ISerializer,
24 | ISerializer,
25 | ISerializer,
26 | ISerializer
27 | {
28 | /// Gets a singleton of the VariantNumberSerializer
29 | public static readonly VariantNumberSerializer Instance = new VariantNumberSerializer();
30 | /// Gets a typed version of the VariantNumberSerializer
31 | public static readonly ISerializer Int32 = Instance;
32 | /// Gets a typed version of the VariantNumberSerializer
33 | public static readonly ISerializer UInt32 = Instance;
34 | /// Gets a typed version of the VariantNumberSerializer
35 | public static readonly ISerializer Int64 = Instance;
36 | /// Gets a typed version of the VariantNumberSerializer
37 | public static readonly ISerializer UInt64 = Instance;
38 |
39 | #region ISerializer Members
40 |
41 | void ISerializer.WriteTo(int value, Stream stream)
42 | {
43 | ((ISerializer)this).WriteTo(unchecked((uint)value), stream);
44 | }
45 |
46 | int ISerializer.ReadFrom(Stream stream)
47 | {
48 | return unchecked((int)((ISerializer)this).ReadFrom(stream));
49 | }
50 |
51 | #endregion
52 | #region ISerializer Members
53 |
54 | void ISerializer.WriteTo(uint value, Stream stream)
55 | {
56 | unchecked
57 | {
58 | while (value > 0x7F)
59 | {
60 | stream.WriteByte((byte)(value | 0x80));
61 | value >>= 7;
62 | }
63 | stream.WriteByte((byte)value);
64 | }
65 | }
66 |
67 | uint ISerializer.ReadFrom(Stream stream)
68 | {
69 | const uint mask = 0x7f;
70 | int last;
71 | uint value = 0;
72 | int shift = 0;
73 | do
74 | {
75 | last = stream.ReadByte();
76 | Check.Assert(last != -1);
77 |
78 | value = (value & ~(mask << shift)) + ((uint)last << shift);
79 | shift += 7;
80 | } while ((last & 0x080) != 0);
81 | return value;
82 | }
83 |
84 | #endregion
85 | #region ISerializer Members
86 |
87 | void ISerializer.WriteTo(long value, Stream stream)
88 | {
89 | ((ISerializer)this).WriteTo(unchecked((ulong)value), stream);
90 | }
91 |
92 | long ISerializer.ReadFrom(Stream stream)
93 | {
94 | return unchecked((long)((ISerializer)this).ReadFrom(stream));
95 | }
96 |
97 | #endregion
98 | #region ISerializer Members
99 |
100 | /// Writes the object to the stream
101 | void ISerializer.WriteTo(ulong value, Stream stream)
102 | {
103 | unchecked
104 | {
105 | while (value > 0x7F)
106 | {
107 | stream.WriteByte((byte)(value | 0x80));
108 | value >>= 7;
109 | }
110 | stream.WriteByte((byte)value);
111 | }
112 | }
113 |
114 | /// Reads the object from a stream
115 | ulong ISerializer.ReadFrom(Stream stream)
116 | {
117 | const ulong mask = 0x7f;
118 | int last;
119 | ulong value = 0;
120 | int shift = 0;
121 | do
122 | {
123 | last = stream.ReadByte();
124 | Check.Assert(last != -1);
125 |
126 | value = (value & ~(mask << shift)) + ((ulong)last << shift);
127 | shift += 7;
128 | } while ((last & 0x080) != 0);
129 | return value;
130 | }
131 |
132 | #endregion
133 | }
134 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Storage/Storage.Memory.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.CodeDom.Compiler;
17 | using System.Collections.Generic;
18 | using System.IO;
19 | using System.Threading;
20 | using CSharpTest.Net.Collections;
21 | using CSharpTest.Net.Serialization;
22 |
23 | namespace CSharpTest.Net.Storage
24 | {
25 | ///
26 | /// Provides an in-memory implementation of the storage services for BPlusTree, useful when testing :)
27 | ///
28 | class BTreeMemoryStore : INodeStorage
29 | {
30 | readonly ISerializer _stringSerializer;
31 | MyStorageHandle _root;
32 |
33 | /// Default in-memory storage
34 | public BTreeMemoryStore()
35 | {
36 | _stringSerializer = PrimitiveSerializer.Instance;
37 | }
38 |
39 | public void Dispose()
40 | {
41 | _root = null;
42 | }
43 |
44 | public IStorageHandle OpenRoot(out bool isNew)
45 | {
46 | isNew = _root == null;
47 | _root = _root ?? new MyStorageHandle("ROOT");
48 | return _root;
49 | }
50 |
51 | public void Reset()
52 | {
53 | _root = null;
54 | }
55 |
56 | public bool TryGetNode(IStorageHandle handleIn, out TNode node, ISerializer serializer)
57 | {
58 | InvalidNodeHandleException.Assert(handleIn is MyStorageHandle);
59 | MyStorageHandle handle = (MyStorageHandle)handleIn;
60 | if (handle.Node != null)
61 | {
62 | node = (TNode)handle.Node;
63 | return true;
64 | }
65 | node = default(TNode);
66 | return false;
67 | }
68 |
69 | [Obsolete("Not supported", true)]
70 | void ISerializer.WriteTo(IStorageHandle value, Stream stream)
71 | { throw new NotSupportedException(); }
72 |
73 | [Obsolete("Not supported", true)]
74 | IStorageHandle ISerializer.ReadFrom(Stream stream)
75 | { throw new NotSupportedException(); }
76 |
77 | public IStorageHandle Create()
78 | {
79 | MyStorageHandle handle = new MyStorageHandle();
80 | return handle;
81 | }
82 |
83 | public void Destroy(IStorageHandle handleIn)
84 | {
85 | InvalidNodeHandleException.Assert(handleIn is MyStorageHandle);
86 | MyStorageHandle handle = (MyStorageHandle)handleIn;
87 |
88 | handle.Clear();
89 | }
90 |
91 | public void Update(IStorageHandle handleIn, ISerializer serializer, T node)
92 | {
93 | InvalidNodeHandleException.Assert(handleIn is MyStorageHandle);
94 | MyStorageHandle handle = (MyStorageHandle)handleIn;
95 | handle.Node = node;
96 | }
97 | [System.Diagnostics.DebuggerDisplay("{_id}")]
98 | class MyStorageHandle : IStorageHandle
99 | {
100 | static int _counter;
101 | readonly string _id;
102 | public MyStorageHandle()
103 | : this(Interlocked.Increment(ref _counter).ToString())
104 | { }
105 | public MyStorageHandle(string id)
106 | { _id = id; }
107 |
108 | internal object Node;
109 |
110 | public void Clear()
111 | { Node = null; }
112 |
113 | public bool Equals(IStorageHandle other)
114 | { return base.Equals(other); }
115 | }
116 | }
117 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/ExclusiveLocking.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Threading;
17 |
18 | namespace CSharpTest.Net.Synchronization
19 | {
20 | ///
21 | /// wraps the reader/writer lock around Monitor
22 | ///
23 | public class ExclusiveLocking : ILockStrategy
24 | {
25 | /// The writer version
26 | int _writeVersion;
27 |
28 | void IDisposable.Dispose() { }
29 |
30 | ///
31 | /// Returns true if the lock was successfully obtained within the timeout specified
32 | ///
33 | public bool TryRead(int timeout)
34 | {
35 | return Monitor.TryEnter(this, timeout);
36 | }
37 |
38 | ///
39 | /// Releases a read lock
40 | ///
41 | public void ReleaseRead()
42 | {
43 | Monitor.Exit(this);
44 | }
45 |
46 | /// Changes every time a write lock is aquired. If WriteVersion == 0, no write locks have been issued.
47 | public int WriteVersion { get { return _writeVersion; } }
48 |
49 | ///
50 | /// Returns true if the lock was successfully obtained within the timeout specified
51 | ///
52 | public bool TryWrite(int timeout)
53 | {
54 | if (Monitor.TryEnter(this, timeout))
55 | {
56 | _writeVersion++;
57 | return true;
58 | }
59 | return false;
60 | }
61 |
62 | ///
63 | /// Releases a writer lock
64 | ///
65 | public void ReleaseWrite()
66 | {
67 | Monitor.Exit(this);
68 | }
69 |
70 | ///
71 | /// Returns a reader lock that can be elevated to a write lock
72 | ///
73 | public ReadLock Read() { return ReadLock.Acquire(this, -1); }
74 |
75 | ///
76 | /// Returns a reader lock that can be elevated to a write lock
77 | ///
78 | ///
79 | public ReadLock Read(int timeout) { return ReadLock.Acquire(this, timeout); }
80 |
81 | ///
82 | /// Returns a read and write lock
83 | ///
84 | public WriteLock Write() { return WriteLock.Acquire(this, -1); }
85 |
86 | ///
87 | /// Returns a read and write lock
88 | ///
89 | ///
90 | public WriteLock Write(int timeout) { return WriteLock.Acquire(this, timeout); }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/ILockStrategy.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Synchronization
18 | {
19 | ///
20 | /// An interface that allows reader/writer locking with the using() statement
21 | ///
22 | public interface ILockStrategy : IDisposable
23 | {
24 | ///
25 | /// Returns a reader lock that can be elevated to a write lock
26 | ///
27 | ReadLock Read();
28 | ///
29 | /// Returns a reader lock that can be elevated to a write lock
30 | ///
31 | ///
32 | ReadLock Read(int timeout);
33 | ///
34 | /// Returns true if the lock was successfully obtained within the timeout specified
35 | ///
36 | bool TryRead(int timeout);
37 | ///
38 | /// Releases a read lock
39 | ///
40 | void ReleaseRead();
41 | ///
42 | /// The the current writer sequence number
43 | ///
44 | int WriteVersion { get; }
45 | ///
46 | /// Returns a read and write lock
47 | ///
48 | WriteLock Write();
49 | ///
50 | /// Returns a read and write lock
51 | ///
52 | ///
53 | WriteLock Write(int timeout);
54 | ///
55 | /// Returns true if the lock was successfully obtained within the timeout specified
56 | ///
57 | bool TryWrite(int timeout);
58 | ///
59 | /// Releases a writer lock
60 | ///
61 | void ReleaseWrite();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/IgnoreLocking.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Synchronization
18 | {
19 | /// Singleton instance of ignore locking
20 | public class IgnoreLockFactory : ILockFactory
21 | {
22 | /// Returns the IgnoreLocking.Instance singleton
23 | public ILockStrategy Create() { return IgnoreLocking.Instance; }
24 | }
25 |
26 | ///
27 | /// wraps the reader/writer lock around Monitor
28 | ///
29 | public class IgnoreLocking : ILockStrategy
30 | {
31 | /// Singleton instance of ignore locking
32 | public static IgnoreLocking Instance = new IgnoreLocking();
33 |
34 | void IDisposable.Dispose() { }
35 |
36 | /// Returns Zero.
37 | public int WriteVersion { get { return 0; } }
38 |
39 | ///
40 | /// Returns true if the lock was successfully obtained within the timeout specified
41 | ///
42 | public bool TryRead(int timeout)
43 | {
44 | return true;
45 | }
46 |
47 | ///
48 | /// Releases a read lock
49 | ///
50 | public void ReleaseRead()
51 | { }
52 |
53 | ///
54 | /// Returns true if the lock was successfully obtained within the timeout specified
55 | ///
56 | public bool TryWrite(int timeout)
57 | {
58 | return true;
59 | }
60 |
61 | ///
62 | /// Releases a writer lock
63 | ///
64 | public void ReleaseWrite()
65 | { }
66 |
67 | ///
68 | /// Returns a reader lock that can be elevated to a write lock
69 | ///
70 | public ReadLock Read() { return new ReadLock(this, true); }
71 |
72 | ///
73 | /// Returns a reader lock that can be elevated to a write lock
74 | ///
75 | ///
76 | public ReadLock Read(int timeout) { return new ReadLock(this, true); }
77 |
78 | ///
79 | /// Returns a read and write lock
80 | ///
81 | public WriteLock Write() { return new WriteLock(this, true); }
82 |
83 | ///
84 | /// Returns a read and write lock
85 | ///
86 | ///
87 | public WriteLock Write(int timeout) { return new WriteLock(this, true); }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/LockFactory.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using CSharpTest.Net.Bases;
17 | using CSharpTest.Net.Interfaces;
18 |
19 | namespace CSharpTest.Net.Synchronization
20 | {
21 | /// A factory that produces instances of ILockStrategy to aquire/release read/write locks
22 | public interface ILockFactory : IFactory
23 | { }
24 |
25 | /// A generic implementation that constructs a lock by type
26 | public class LockFactory : ILockFactory
27 | where T : ILockStrategy, new()
28 | {
29 | /// Returns a new lock of type T
30 | public ILockStrategy Create()
31 | { return new T(); }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/ReadLock.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Synchronization
18 | {
19 | ///
20 | /// Allows a read lock to be disposed or elevated to a write lock
21 | ///
22 | public struct ReadLock : IDisposable
23 | {
24 | /// Acquires the lock within the timeout or throws TimeoutException
25 | ///
26 | public static ReadLock Acquire(ILockStrategy lck, int timeout)
27 | {
28 | if (!lck.TryRead(timeout)) throw new TimeoutException();
29 | return new ReadLock(lck, true);
30 | }
31 |
32 | bool _hasLock;
33 | readonly ILockStrategy _lock;
34 |
35 | /// Tracks an existing read lock on a resource
36 | public ReadLock(ILockStrategy lck, bool locked)
37 | {
38 | _lock = lck;
39 | _hasLock = locked;
40 | }
41 |
42 | /// Acquires a read lock on the resource
43 | public ReadLock(ILockStrategy lck, int timeout)
44 | {
45 | _lock = lck;
46 | _hasLock = lck.TryRead(timeout);
47 | }
48 |
49 | /// Unlocks the resource
50 | [Obsolete("Do not call directly, use a using(...) statement only.", true)]
51 | public void Dispose()
52 | {
53 | if (_hasLock)
54 | _lock.ReleaseRead();
55 | _hasLock = false;
56 | }
57 |
58 | ///
59 | /// Returns true if read access is locked
60 | ///
61 | public bool HasReadLock { get { return _hasLock; } }
62 | }
63 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/ReaderWriterLocking.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Threading;
17 |
18 | namespace CSharpTest.Net.Synchronization
19 | {
20 | ///
21 | /// wraps the System.Threading.ReaderWriterLock lock, does not support read->write upgrades
22 | ///
23 | public class ReaderWriterLocking : ILockStrategy
24 | {
25 | private readonly ReaderWriterLock _lock;
26 | ///
27 | /// wraps the reader/writer lock
28 | ///
29 | public ReaderWriterLocking() : this(new ReaderWriterLock())
30 | { }
31 | ///
32 | /// wraps the reader/writer lock
33 | ///
34 | public ReaderWriterLocking(ReaderWriterLock lck)
35 | { _lock = lck; }
36 |
37 | void IDisposable.Dispose() { }
38 |
39 | /// Changes every time a write lock is aquired. If WriteVersion == 0, no write locks have been issued.
40 | public int WriteVersion { get { return _lock.WriterSeqNum; } }
41 |
42 | ///
43 | /// Returns true if the lock was successfully obtained within the timeout specified
44 | ///
45 | [System.Diagnostics.DebuggerNonUserCode]
46 | public bool TryRead(int timeout)
47 | {
48 | try
49 | {
50 | _lock.AcquireReaderLock(timeout);
51 | return true;
52 | }
53 | catch (ApplicationException)
54 | { return false; }
55 | }
56 |
57 | ///
58 | /// Releases a read lock
59 | ///
60 | public void ReleaseRead()
61 | {
62 | _lock.ReleaseReaderLock();
63 | }
64 |
65 | ///
66 | /// Returns true if the lock was successfully obtained within the timeout specified
67 | ///
68 | [System.Diagnostics.DebuggerNonUserCode]
69 | public bool TryWrite(int timeout)
70 | {
71 | try
72 | {
73 | _lock.AcquireWriterLock(timeout);
74 | return true;
75 | }
76 | catch (ApplicationException)
77 | { return false; }
78 | }
79 |
80 | ///
81 | /// Releases a writer lock
82 | ///
83 | public void ReleaseWrite()
84 | {
85 | _lock.ReleaseWriterLock();
86 | }
87 |
88 | ///
89 | /// Returns a reader lock that can be elevated to a write lock
90 | ///
91 | public ReadLock Read() { return ReadLock.Acquire(this, -1); }
92 |
93 | ///
94 | /// Returns a reader lock that can be elevated to a write lock
95 | ///
96 | ///
97 | public ReadLock Read(int timeout) { return ReadLock.Acquire(this, timeout); }
98 |
99 | ///
100 | /// Returns a read and write lock
101 | ///
102 | public WriteLock Write() { return WriteLock.Acquire(this, -1); }
103 |
104 | ///
105 | /// Returns a read and write lock
106 | ///
107 | ///
108 | public WriteLock Write(int timeout) { return WriteLock.Acquire(this, timeout); }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/SafeLock.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Threading;
17 |
18 | namespace CSharpTest.Net.Synchronization
19 | {
20 | ///
21 | /// Used to acquire a lock(object) with a timeout, either specified or the default of 2 minutes.
22 | ///
23 | public struct SafeLock : IDisposable
24 | {
25 | ///
26 | /// The default timeout value used when one is not provided to the constructor
27 | ///
28 | public const int DefaultTimeout = 120000;
29 |
30 | object _sync;
31 |
32 | ///
33 | /// Acquires the monitor lock on the object within 2 minutes, or throws TimeoutException
34 | ///
35 | public SafeLock(object monitor)
36 | : this(monitor, DefaultTimeout)
37 | { }
38 |
39 | ///
40 | /// Acquires the monitor lock on the object within timeoutMilliseconds, or throws TimeoutException
41 | ///
42 | public SafeLock(object monitor, int timeoutMilliseconds)
43 | {
44 | if (!Monitor.TryEnter(monitor, timeoutMilliseconds))
45 | throw new TimeoutException();
46 | _sync = monitor;
47 | }
48 |
49 | /// Releases the lock acquired by the constructor
50 | [Obsolete("Do not call directly, use a using(...) statement only.", true)]
51 | public void Dispose()
52 | {
53 | if (_sync != null)
54 | {
55 | object monitor = _sync;
56 | _sync = null;
57 | Monitor.Exit(monitor);
58 | }
59 | }
60 | }
61 |
62 | ///
63 | /// Exactly as SafeLock except that <T> specifies the exception type to throw.
64 | /// Used to acquire a lock(object) with a timeout, either specified or the default of 2 minutes.
65 | ///
66 | public struct SafeLock : IDisposable
67 | where TException : Exception, new()
68 | {
69 | object _sync;
70 |
71 | ///
72 | /// Acquires the monitor lock on the object within 2 minutes, or throws TimeoutException
73 | ///
74 | public SafeLock(object monitor)
75 | : this(monitor, SafeLock.DefaultTimeout)
76 | { }
77 |
78 | ///
79 | /// Acquires the monitor lock on the object within timeoutMilliseconds, or throws TimeoutException
80 | ///
81 | public SafeLock(object monitor, int timeoutMilliseconds)
82 | {
83 | if (!Monitor.TryEnter(monitor, timeoutMilliseconds))
84 | throw new TException();
85 | _sync = monitor;
86 | }
87 |
88 | /// Releases the lock acquired by the constructor
89 | [Obsolete("Do not call directly, use a using(...) statement only.", true)]
90 | public void Dispose()
91 | {
92 | if (_sync != null)
93 | {
94 | object monitor = _sync;
95 | _sync = null;
96 | Monitor.Exit(monitor);
97 | }
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/WriteLock.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Synchronization
18 | {
19 | ///
20 | /// Allows a write lock to be disposed
21 | ///
22 | public struct WriteLock : IDisposable
23 | {
24 | /// Acquires the lock within the timeout or throws TimeoutException
25 | ///
26 | public static WriteLock Acquire(ILockStrategy lck, int timeout)
27 | {
28 | if(!lck.TryWrite(timeout)) throw new TimeoutException();
29 | return new WriteLock(lck, true);
30 | }
31 |
32 | bool _hasLock;
33 | readonly ILockStrategy _lock;
34 |
35 | /// Tracks an existing read lock on a resource
36 | public WriteLock(ILockStrategy lck, bool locked)
37 | {
38 | _lock = lck;
39 | _hasLock = locked;
40 | }
41 |
42 | /// Acquires a read lock on the resource
43 | public WriteLock(ILockStrategy lck, int timeout)
44 | {
45 | _lock = lck;
46 | _hasLock = lck.TryWrite(timeout);
47 | }
48 |
49 | ///
50 | /// Returns true if write access is locked
51 | ///
52 | public bool HasWriteLock { get { return _hasLock; } }
53 |
54 | /// Unlocks the resource
55 | [Obsolete("Do not call directly, use a using(...) statement only.", true)]
56 | public void Dispose()
57 | {
58 | if (_hasLock)
59 | _lock.ReleaseWrite();
60 | _hasLock = false;
61 | }
62 | }
63 | }
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Synchronization/WriterOnlyLocking.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | #define SUPPORT_RECURSION
16 | using System;
17 | using System.Threading;
18 |
19 | namespace CSharpTest.Net.Synchronization
20 | {
21 | ///
22 | /// provides a writer-only lock around Monitor. The TryRead/ReleaseRead methods are no-ops and
23 | /// always return true.
24 | ///
25 | public class WriterOnlyLocking : ILockStrategy
26 | {
27 | /// The writer version
28 | int _writeVersion;
29 |
30 | void IDisposable.Dispose() { }
31 |
32 | ///
33 | /// Returns true if the lock was successfully obtained within the timeout specified
34 | ///
35 | public bool TryRead(int timeout)
36 | { return true; }
37 |
38 | ///
39 | /// Releases a read lock
40 | ///
41 | public void ReleaseRead()
42 | { }
43 |
44 | /// Changes every time a write lock is aquired. If WriteVersion == 0, no write locks have been issued.
45 | public int WriteVersion { get { return _writeVersion; } }
46 |
47 | ///
48 | /// Returns true if the lock was successfully obtained within the timeout specified
49 | ///
50 | public bool TryWrite(int timeout)
51 | {
52 | if (Monitor.TryEnter(this, timeout))
53 | {
54 | _writeVersion++;
55 | return true;
56 | }
57 | return false;
58 | }
59 |
60 | ///
61 | /// Releases a writer lock
62 | ///
63 | public void ReleaseWrite()
64 | {
65 | Monitor.Exit(this);
66 | }
67 |
68 | ///
69 | /// Returns a reader lock that can be elevated to a write lock
70 | ///
71 | public ReadLock Read() { return ReadLock.Acquire(this, -1); }
72 |
73 | ///
74 | /// Returns a reader lock that can be elevated to a write lock
75 | ///
76 | ///
77 | public ReadLock Read(int timeout) { return ReadLock.Acquire(this, timeout); }
78 |
79 | ///
80 | /// Returns a read and write lock
81 | ///
82 | public WriteLock Write() { return WriteLock.Acquire(this, -1); }
83 |
84 | ///
85 | /// Returns a read and write lock
86 | ///
87 | ///
88 | public WriteLock Write(int timeout) { return WriteLock.Acquire(this, timeout); }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.Collections/Utils/WeakReference.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2011-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 |
17 | namespace CSharpTest.Net.Utils
18 | {
19 | ///
20 | /// A strong-typed derivation of the WeakReference class
21 | ///
22 | [Serializable]
23 | public class WeakReference : WeakReference
24 | where T : class
25 | {
26 | /// Creates a new WeakReference that keeps track of target.
27 | public WeakReference(T instance)
28 | : base(instance)
29 | { }
30 |
31 | ///
32 | protected WeakReference(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
33 | : base(info, context)
34 | { }
35 |
36 | ///
37 | /// Gets an indication whether the object referenced by the current object has been garbage collected.
38 | ///
39 | public override bool IsAlive { get { return base.IsAlive && base.Target is T; } }
40 |
41 | /// Gets or sets the Object stored in the handle if it's accessible.
42 | public new T Target
43 | {
44 | get { return base.Target as T; }
45 | set { base.Target = value; }
46 | }
47 |
48 | /// Returns true if the Object was retrieved.
49 | public bool TryGetTarget(out T value)
50 | {
51 | value = base.Target as T;
52 | return value != null;
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/CSharpTest.Net.CollectionsTest/Bases/Comparable.cs:
--------------------------------------------------------------------------------
1 | #region Copyright 2010-2014 by Roger Knapp, Licensed under the Apache License, Version 2.0
2 | /* Licensed under the Apache License, Version 2.0 (the "License");
3 | * you may not use this file except in compliance with the License.
4 | * You may obtain a copy of the License at
5 | *
6 | * http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software
9 | * distributed under the License is distributed on an "AS IS" BASIS,
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 | * See the License for the specific language governing permissions and
12 | * limitations under the License.
13 | */
14 | #endregion
15 | using System;
16 | using System.Collections.Generic;
17 | using System.Diagnostics;
18 | using System.ComponentModel;
19 |
20 | namespace CSharpTest.Net.Bases
21 | {
22 | /// Provides a base-class for non-reference comparison of objects
23 | [System.Diagnostics.DebuggerNonUserCode]
24 | public abstract class Comparable : Equatable, IComparable, IComparable
25 | where T : Comparable
26 | {
27 | /// returns a non-reference comparer for this class
28 | public static new readonly EqualityComparer Comparer = new EqualityComparer();
29 |
30 | /// Returns true if the object is equal
31 | public override bool Equals(T other)
32 | { return ((object)other) == null ? false : (0 == this.CompareTo(other)); }
33 |
34 | /// Compares with another object of T
35 | public abstract int CompareTo(T other);
36 |
37 | int IComparable.CompareTo(object obj)
38 | { return this.CompareTo(obj as T); }
39 |
40 | /// Compares two objects
41 | public static bool operator <(Comparable a, Comparable