Skip to content

Structural equals for infer and IUrlParameter types #3126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 19, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/Nest/CommonAbstractions/Extensions/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ internal static bool HasAny<T>(this IEnumerable<T> list)
return list != null && list.Any();
}

internal static bool IsEmpty<T>(this IEnumerable<T> list)
{
if (list == null) return true;
var enumerable = list as T[] ?? list.ToArray();
return !enumerable.Any() || enumerable.All(t => t == null);
}

internal static void ThrowIfNull<T>(this T value, string name, string message = null)
{
if (value == null && message.IsNullOrEmpty()) throw new ArgumentNullException(name);
Expand All @@ -193,6 +200,16 @@ internal static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
internal static bool IsNullOrEmptyCommaSeparatedList(this string value, out string[] split)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use a .All(...) LINQ extension? might save initialising the array.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...PEBKAC, just noticed the out parameter!

{
split = null;
if (string.IsNullOrWhiteSpace(value)) return true;
split = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Where(t=>!t.IsNullOrEmpty())
.Select(t=>t.Trim())
.ToArray();
return split.Length == 0;
}

internal static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> handler)
{
Expand Down Expand Up @@ -282,5 +299,13 @@ private static async Task ProcessAsync<TSource, TResult>(
additionalRateLimiter?.Release();
}
}

internal static bool NullOrEquals<T>(this T o, T other)
{
if (o == null && other == null) return true;
if (o == null || other == null) return false;
return o.Equals(other);
}

}
}
24 changes: 19 additions & 5 deletions src/Nest/CommonAbstractions/Infer/ActionIds/ActionIds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;

namespace Nest
{
[DebuggerDisplay("{DebugDisplay,nq}")]
public class ActionIds : IUrlParameter
public class ActionIds : IUrlParameter, IEquatable<ActionIds>
{
private readonly List<string> _actionIds;
internal IReadOnlyList<string> Ids => _actionIds;

public ActionIds(IEnumerable<string> actionIds)
{
Expand All @@ -31,8 +30,23 @@ public ActionIds(string actionIds)

string IUrlParameter.GetString(IConnectionConfigurationValues settings) => string.Join(",", this._actionIds);

public static implicit operator ActionIds(string actionIds) => new ActionIds(actionIds);
public static implicit operator ActionIds(string actionIds) => actionIds.IsNullOrEmptyCommaSeparatedList(out var list) ? null : new ActionIds(list);

public static implicit operator ActionIds(string[] actionIds) => new ActionIds(actionIds);
public static implicit operator ActionIds(string[] actionIds) => actionIds.IsEmpty() ? null : new ActionIds(actionIds);

public bool Equals(ActionIds other)
{
if (this.Ids == null && other.Ids == null) return true;
if (this.Ids == null || other.Ids == null) return false;
return this.Ids.Count == other.Ids.Count && !this.Ids.Except(other.Ids).Any();
}

public override bool Equals(object obj) => obj is ActionIds other && Equals(other);

public override int GetHashCode() => this._actionIds.GetHashCode();

public static bool operator ==(ActionIds left, ActionIds right) => Equals(left, right);

public static bool operator !=(ActionIds left, ActionIds right) => !Equals(left, right);
}
}
33 changes: 26 additions & 7 deletions src/Nest/CommonAbstractions/Infer/CategoryId/CategoryId.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
using System.Globalization;
using System;
using System.Globalization;
using Elasticsearch.Net;

namespace Nest
{
public class CategoryId : IUrlParameter
public class CategoryId : IUrlParameter, IEquatable<CategoryId>
{
private readonly long _categoryId;
internal readonly long Value;

public CategoryId(long categoryId)
public CategoryId(long value) => Value = value;

public static implicit operator CategoryId(long categoryId) => new CategoryId(categoryId);
public static implicit operator long(CategoryId categoryId) => categoryId.Value;

// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public string GetString(IConnectionConfigurationValues settings) => Value.ToString(CultureInfo.InvariantCulture);

public bool Equals(CategoryId other) => this.Value == other.Value;

public override bool Equals(object obj)
{
_categoryId = categoryId;
switch (obj)
{
case int l: return this.Value == l;
case long l: return this.Value == l;
case CategoryId i: return this.Value == i.Value;
default: return false;
}
}

public static implicit operator CategoryId(long categoryId) => new CategoryId(categoryId);
public override int GetHashCode() => this.Value.GetHashCode();

public static bool operator ==(CategoryId left, CategoryId right) => Equals(left, right);

public string GetString(IConnectionConfigurationValues settings) => _categoryId.ToString(CultureInfo.InvariantCulture);
public static bool operator !=(CategoryId left, CategoryId right) => !Equals(left, right);
}
}
39 changes: 35 additions & 4 deletions src/Nest/CommonAbstractions/Infer/DocumentPath/DocumentPath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public interface IDocumentPath
TypeName Type { get; set; }
}

public class DocumentPath<T> : IDocumentPath where T : class
public class DocumentPath<T> : IEquatable<DocumentPath<T>>, IDocumentPath where T : class
{
internal IDocumentPath Self => this;
internal T Document { get; set; }
Expand All @@ -28,10 +28,10 @@ public DocumentPath(Id id)
public static DocumentPath<T> Id(Id id) => new DocumentPath<T>(id);
public static DocumentPath<T> Id(T @object) => new DocumentPath<T>(@object);

public static implicit operator DocumentPath<T>(T @object) => new DocumentPath<T>(@object);
public static implicit operator DocumentPath<T>(Id id) => new DocumentPath<T>(id);
public static implicit operator DocumentPath<T>(T @object) => @object == null ? null : new DocumentPath<T>(@object);
public static implicit operator DocumentPath<T>(Id id) => id == null ? null : new DocumentPath<T>(id);
public static implicit operator DocumentPath<T>(long id) => new DocumentPath<T>(id);
public static implicit operator DocumentPath<T>(string id) => new DocumentPath<T>(id);
public static implicit operator DocumentPath<T>(string id) => id.IsNullOrEmpty() ? null : new DocumentPath<T>(id);
public static implicit operator DocumentPath<T>(Guid id) => new DocumentPath<T>(id);

public DocumentPath<T> Index(IndexName index)
Expand All @@ -46,5 +46,36 @@ public DocumentPath<T> Type(TypeName type)
Self.Type = type;
return this;
}

public override int GetHashCode()
{
unchecked
{
var hashCode = Self.Type?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ (Self.Index?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (Self.Id?.GetHashCode() ?? 0);
return hashCode;
}
}

public bool Equals(DocumentPath<T> other)
{
IDocumentPath o = other, s = Self;
return s.Index.NullOrEquals(o.Index) && s.Type.NullOrEquals(o.Type) && s.Id.NullOrEquals(o.Id)
&& (this.Document?.Equals(other.Document) ?? true);
}

public override bool Equals(object obj)
{
switch (obj)
{
case DocumentPath<T> d: return this.Equals(d);
default: return false;
}
}

public static bool operator ==(DocumentPath<T> x, DocumentPath<T> y) => Equals(x, y);

public static bool operator !=(DocumentPath<T> x, DocumentPath<T> y)=> !Equals(x, y);
}
}
54 changes: 19 additions & 35 deletions src/Nest/CommonAbstractions/Infer/Field/Field.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,16 @@ public Field(string name, double? boost = null)

public Field(Expression expression, double? boost = null)
{
if (expression == null) throw new ArgumentNullException(nameof(expression));
Expression = expression;
Expression = expression ?? throw new ArgumentNullException(nameof(expression));
Boost = boost;
Type type;
_comparisonValue = expression.ComparisonValueFromExpression(out type);
_comparisonValue = expression.ComparisonValueFromExpression(out var type);
_type = type;
CachableExpression = !new HasVariableExpressionVisitor(expression).Found;
}

public Field(PropertyInfo property, double? boost = null)
{
if (property == null) throw new ArgumentNullException(nameof(property));
Property = property;
Property = property ?? throw new ArgumentNullException(nameof(property));
Boost = boost;
_comparisonValue = property;
_type = property.DeclaringType;
Expand All @@ -74,26 +71,17 @@ private static string ParseFieldName(string name, out double? boost)
if (name == null) return null;

var parts = name.Split(new [] { '^' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length <= 1) return name.Trim();
if (parts.Length <= 1) return name;
name = parts[0];
boost = double.Parse(parts[1], CultureInfo.InvariantCulture);
return name.Trim();
return name;
}

public static implicit operator Field(string name)
{
return name.IsNullOrEmpty() ? null : new Field(name);
}
public static implicit operator Field(string name) => name.IsNullOrEmpty() ? null : new Field(name);

public static implicit operator Field(Expression expression)
{
return expression == null ? null : new Field(expression);
}
public static implicit operator Field(Expression expression) => expression == null ? null : new Field(expression);

public static implicit operator Field(PropertyInfo property)
{
return property == null ? null : new Field(property);
}
public static implicit operator Field(PropertyInfo property) => property == null ? null : new Field(property);

public override int GetHashCode()
{
Expand All @@ -114,27 +102,23 @@ public bool Equals(Field other)

public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return this.Equals(obj as Field);
switch (obj)
{
case string s: return this.Equals(s);
case PropertyInfo p: return this.Equals(p);
case Field f: return this.Equals(f);
default: return false;
}
}

public static bool operator ==(Field x, Field y)
{
return Equals(x, y);
}
public static bool operator ==(Field x, Field y) => Equals(x, y);

public static bool operator !=(Field x, Field y)
{
return !(x == y);
}
public static bool operator !=(Field x, Field y)=> !Equals(x, y);

string IUrlParameter.GetString(IConnectionConfigurationValues settings)
{
var nestSettings = settings as IConnectionSettingsValues;
if (nestSettings == null)
throw new Exception("Tried to pass field name on querystring but it could not be resolved because no nest settings are available");
if (!(settings is IConnectionSettingsValues nestSettings))
throw new ArgumentNullException(nameof(settings), $"Can not resolve {nameof(Field)} if no {nameof(IConnectionSettingsValues)} is provided");

return nestSettings.Inferrer.Field(this);
}
Expand Down
64 changes: 48 additions & 16 deletions src/Nest/CommonAbstractions/Infer/Fields/Fields.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,40 @@ namespace Nest
{
[ContractJsonConverter(typeof(FieldsJsonConverter))]
[DebuggerDisplay("{DebugDisplay,nq}")]
public class Fields : IUrlParameter, IEnumerable<Field>
public class Fields : IUrlParameter, IEnumerable<Field>, IEquatable<Fields>
{
internal readonly List<Field> ListOfFields;

string IUrlParameter.GetString(IConnectionConfigurationValues settings) =>
string.Join(",", ListOfFields.Select(f => ((IUrlParameter)f).GetString(settings)));
string IUrlParameter.GetString(IConnectionConfigurationValues settings)
{
if (!(settings is IConnectionSettingsValues nestSettings))
throw new ArgumentNullException(nameof(settings), $"Can not resolve {nameof(Fields)} if no {nameof(IConnectionSettingsValues)} is provided");

private string DebugDisplay =>
$"Count: {ListOfFields.Count} [" + string.Join(",", ListOfFields.Select((t, i) => $"({i + 1}: {t.DebugDisplay})")) + "]";
return string.Join(",", ListOfFields.Where(f => f != null).Select(f => ((IUrlParameter)f).GetString(nestSettings)));
}

private string DebugDisplay =>
$"Count: {ListOfFields.Count} [" + string.Join(",", ListOfFields.Select((t, i) => $"({i + 1}: {t?.DebugDisplay ?? "NULL"})")) + "]";

internal Fields() { this.ListOfFields = new List<Field>(); }
internal Fields(IEnumerable<Field> fieldNames) { this.ListOfFields = fieldNames.ToList(); }

public static implicit operator Fields(string[] fields) => new Fields(fields.Select(f => (Field)f));
public static implicit operator Fields(string[] fields) => fields.IsEmpty() ? null : new Fields(fields.Select(f => (Field)f));

public static implicit operator Fields(string field) => field.IsNullOrEmptyCommaSeparatedList(out var split)
? null : new Fields(split.Select(f=>(Field)f));

public static implicit operator Fields(Expression[] fields) => fields.IsEmpty() ? null : new Fields(fields.Select(f => (Field)f));

public static implicit operator Fields(string field) =>
new Fields(field.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries).Select(f=>(Field)f));
public static implicit operator Fields(Expression field) => field == null ? null : new Fields(new [] { (Field)field });

public static implicit operator Fields(Expression[] fields) => new Fields(fields.Select(f => (Field)f));
public static implicit operator Fields(Field field) => field == null ? null : new Fields(new[] { field });

public static implicit operator Fields(Expression field) => new Fields(new [] { (Field)field });
public static implicit operator Fields(PropertyInfo field) => field == null ? null : new Fields(new Field[] { field });

public static implicit operator Fields(Field field) => new Fields(new[] { field });
public static implicit operator Fields(PropertyInfo[] fields) => fields.IsEmpty() ? null : new Fields(fields.Select(f=>(Field)f));

public static implicit operator Fields(Field[] fields) => new Fields(fields);
public static implicit operator Fields(Field[] fields) => fields.IsEmpty() ? null : new Fields(fields);

public Fields And<T>(Expression<Func<T, object>> field, double? boost = null) where T : class
{
Expand Down Expand Up @@ -80,14 +88,38 @@ public Fields And(params Field[] fields)
return this;
}

public IEnumerator<Field> GetEnumerator()
public IEnumerator<Field> GetEnumerator() => this.ListOfFields.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

public static bool operator ==(Fields left, Fields right) => Equals(left, right);

public static bool operator !=(Fields left, Fields right) => !Equals(left, right);

public bool Equals(Fields other) => EqualsAllFields(this.ListOfFields, other.ListOfFields);

public override bool Equals(object obj)
{
return this.ListOfFields.GetEnumerator();
switch (obj)
{
case Fields f: return Equals(f);
case string s: return Equals(s);
case Field fn: return Equals(fn);
case Field[] fns: return Equals(fns);
case Expression e: return Equals(e);
case Expression[] es: return Equals(es);
default: return false;
}
}

IEnumerator IEnumerable.GetEnumerator()
private static bool EqualsAllFields(IReadOnlyList<Field> thisTypes, IReadOnlyList<Field> otherTypes)
{
return this.GetEnumerator();
if (thisTypes == null && otherTypes == null) return true;
if (thisTypes == null || otherTypes == null) return false;
if (thisTypes.Count != otherTypes.Count) return false;
return thisTypes.Count == otherTypes.Count && !thisTypes.Except(otherTypes).Any();
}

public override int GetHashCode() => this.ListOfFields.GetHashCode();
}
}
Loading