Skip to content

Commit

Permalink
Add discriminator value to union fields messages (#131)
Browse files Browse the repository at this point in the history
Deserialized union fields now hold their discriminator value under the
property key "$discriminator", as per [DDS JSON
spec](https://www.omg.org/spec/DDS-JSON/1.0/Beta1/PDF).
  • Loading branch information
snosenzo authored Feb 13, 2024
1 parent 586ee40 commit 3d9831e
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/omgidl-serialization/src/MessageReader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CdrWriter, EncapsulationKind } from "@foxglove/cdr";
import { parseIDL } from "@foxglove/omgidl-parser";

import { MessageReader } from "./MessageReader";
import { UNION_DISCRIMINATOR_PROPERTY_KEY } from "./constants";

const serializeString = (str: string): Uint8Array => {
const data = Buffer.from(str, "utf8");
Expand Down Expand Up @@ -771,6 +772,7 @@ module builtin_interfaces {

expect(msgout).toEqual({
color: {
[UNION_DISCRIMINATOR_PROPERTY_KEY]: 3,
gray: 55,
},
});
Expand Down Expand Up @@ -811,6 +813,7 @@ module builtin_interfaces {

expect(msgout).toEqual({
color: {
[UNION_DISCRIMINATOR_PROPERTY_KEY]: 0,
rgb: Uint8Array.from([255, 0, 0]),
},
});
Expand Down
3 changes: 3 additions & 0 deletions packages/omgidl-serialization/src/MessageReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
StructDeserializationInfo,
UnionDeserializationInfo,
} from "./DeserializationInfoCache";
import { UNION_DISCRIMINATOR_PROPERTY_KEY } from "./constants";

export class MessageReader<T = unknown> {
rootDeserializationInfo: ComplexDeserializationInfo;
Expand Down Expand Up @@ -125,7 +126,9 @@ export class MessageReader<T = unknown> {
}

const fieldDeserInfo = this.deserializationInfoCache.buildFieldDeserInfo(caseDefType);

return {
[UNION_DISCRIMINATOR_PROPERTY_KEY]: discriminatorValue,
[caseDefType.name]: this.readMemberFieldValue(
fieldDeserInfo,
reader,
Expand Down
2 changes: 2 additions & 0 deletions packages/omgidl-serialization/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/** Per: https://www.omg.org/spec/DDS-JSON/1.0/Beta1/PDF */
export const UNION_DISCRIMINATOR_PROPERTY_KEY = "$discriminator";
1 change: 1 addition & 0 deletions packages/omgidl-serialization/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./MessageReader";
export * from "./MessageWriter";
export * from "./constants";

0 comments on commit 3d9831e

Please sign in to comment.