1 | namespace HeuristicLab.Problems.ProgramSynthesis.Push.Expressions {
|
---|
2 | using System;
|
---|
3 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
4 | using HeuristicLab.Problems.ProgramSynthesis.Push.Data.Pool;
|
---|
5 |
|
---|
6 | [Serializable]
|
---|
7 | [StorableClass]
|
---|
8 | public abstract class StatefulExpression<T> : Expression, IPooledObject {
|
---|
9 | [Storable]
|
---|
10 | public T State { get; protected set; }
|
---|
11 | [NonSerialized]
|
---|
12 | private int? hashCode;
|
---|
13 | [NonSerialized]
|
---|
14 | private string stringRepresentation;
|
---|
15 |
|
---|
16 | protected StatefulExpression(T state) {
|
---|
17 | State = state;
|
---|
18 | }
|
---|
19 |
|
---|
20 | [StorableConstructor]
|
---|
21 | protected StatefulExpression(bool deserializing) : base(deserializing) { }
|
---|
22 |
|
---|
23 | protected virtual int CalcHashCode() {
|
---|
24 | var hash = 19 * 31 + GetType().FullName.GetHashCode();
|
---|
25 | hash = hash * 31 + State.GetHashCode();
|
---|
26 |
|
---|
27 | return hash;
|
---|
28 | }
|
---|
29 |
|
---|
30 | protected virtual string GetStringRepresentation() {
|
---|
31 | return State.ToString();
|
---|
32 | }
|
---|
33 |
|
---|
34 | public override string StringRepresentation
|
---|
35 | {
|
---|
36 | get
|
---|
37 | {
|
---|
38 | return stringRepresentation ?? (stringRepresentation = GetStringRepresentation());
|
---|
39 | }
|
---|
40 | }
|
---|
41 |
|
---|
42 | public override bool Equals(object obj) {
|
---|
43 | if (ReferenceEquals(this, obj))
|
---|
44 | return true;
|
---|
45 |
|
---|
46 | if (GetType() != obj.GetType())
|
---|
47 | return false;
|
---|
48 |
|
---|
49 | var other = (StatefulExpression<T>)obj;
|
---|
50 |
|
---|
51 | return ReferenceEquals(State, other.State) ||
|
---|
52 | GetHashCode() == other.GetHashCode();
|
---|
53 | }
|
---|
54 |
|
---|
55 | public bool Equals(StatefulExpression<T> obj) {
|
---|
56 | if (ReferenceEquals(this, obj))
|
---|
57 | return true;
|
---|
58 |
|
---|
59 | if (GetType() != obj.GetType())
|
---|
60 | return false;
|
---|
61 |
|
---|
62 | return ReferenceEquals(State, obj.State) ||
|
---|
63 | GetHashCode() == obj.GetHashCode();
|
---|
64 | }
|
---|
65 |
|
---|
66 | public override int GetHashCode() {
|
---|
67 | if (hashCode == null) hashCode = CalcHashCode();
|
---|
68 | return hashCode.Value;
|
---|
69 | }
|
---|
70 |
|
---|
71 | public void Reset() {
|
---|
72 | State = default(T);
|
---|
73 | }
|
---|
74 | }
|
---|
75 | } |
---|