Skip to content

Commit

Permalink
Refactor some Node.opCmp code (#295)
Browse files Browse the repository at this point in the history
* Node.opCmp: Simplify tag comparison

The previous code had two nested ternary.
The new code should be a bit more readable, even if it reuses the same comparison twice.

* Node.opCmp: Reduce visibility of variables
  • Loading branch information
Geod24 authored Jun 28, 2022
1 parent 85f3d1d commit 339d0c6
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions source/dyaml/node.d
Original file line number Diff line number Diff line change
Expand Up @@ -1974,10 +1974,14 @@ struct Node
/// Compare with another _node.
int opCmp(const ref Node rhs) const @safe
{
// Compare tags - if equal or both null, we need to compare further.
const tagCmp = (tag_ is null) ? (rhs.tag_ is null) ? 0 : -1
: (rhs.tag_ is null) ? 1 : std.algorithm.comparison.cmp(tag_, rhs.tag_);
if(tagCmp != 0){return tagCmp;}
const bool hasNullTag = this.tag_ is null;
// Only one of them is null: we can order nodes
if ((hasNullTag) ^ (rhs.tag is null))
return hasNullTag ? -1 : 1;
// Either both `null` or both have a value
if (!hasNullTag)
if (int result = std.algorithm.comparison.cmp(tag_, rhs.tag_))
return result;

static int cmp(T1, T2)(T1 a, T2 b)
{
Expand All @@ -1987,13 +1991,12 @@ struct Node
}

// Compare validity: if both valid, we have to compare further.
const v1 = isValid;
const v2 = rhs.isValid;
if(!v1){return v2 ? -1 : 0;}
if(!v2){return 1;}

const typeCmp = cmp(type, rhs.type);
if(typeCmp != 0){return typeCmp;}
if (!this.isValid())
return rhs.isValid() ? -1 : 0;
if (!rhs.isValid())
return 1;
if (const typeCmp = cmp(type, rhs.type))
return typeCmp;

static int compareCollections(T)(const ref Node lhs, const ref Node rhs)
{
Expand Down

0 comments on commit 339d0c6

Please sign in to comment.