Skip to content

Commit

Permalink
Add mergeFrom to merge two messages
Browse files Browse the repository at this point in the history
Requested in #109
  • Loading branch information
msoucy committed May 17, 2017
1 parent 1707188 commit 76f074e
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
19 changes: 19 additions & 0 deletions import/dproto/attributes.d
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,25 @@ template ProtoAccessors()
}
}

void mergeFrom(this This)(auto ref This rhs)
{
import std.traits : Identity;
import dproto.attributes;

foreach(__member; ProtoFields!this) {
alias __lmember = Identity!(__traits(getMember, this, __member));
alias T = typeof(__lmember);

static if(is(T : const string) || is(T : const(ubyte)[])) {
__lmember = __traits(getMember, rhs, __member);
} else static if(is(T : const(U)[], U)) {
__lmember ~= __traits(getMember, rhs, __member);
} else {
__lmember = __traits(getMember, rhs, __member);
}
}
}

version(Have_painlessjson) {
auto toJson() const {
import painlessjson;
Expand Down
52 changes: 52 additions & 0 deletions import/dproto/unittests.d
Original file line number Diff line number Diff line change
Expand Up @@ -1024,3 +1024,55 @@ unittest
assert(proto.a1.foo1 == proto.a2.foo1);
}

unittest
{
mixin ProtocolBufferFromString!"
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 0;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
";

Person t;
t.name = "Max Musterman";
t.id = 3;
t.email = "[email protected]";

Person.PhoneNumber pn1;
pn1.number = "0123456789";
pn1.type = Person.PhoneType.WORK;
t.phone ~= pn1;

Person t2 = t;
t2.id = 5;
t2.email = "[email protected]";

Person.PhoneNumber pn2;
pn2.number = "9876543210";
pn2.type = Person.PhoneType.HOME;
t2.phone = [pn2];

import std.stdio;
t.mergeFrom(t2);
assert(t.phone.length == 2);
assert(t.phone[0] == pn1);
assert(t.phone[1] == pn2);
assert(t.id == t.id);
assert(t.email == t2.email);

}

0 comments on commit 76f074e

Please sign in to comment.