chrisdew / protobuf

Protocol Buffers for Node.JS
http://code.google.com/p/protobuf-for-node/
Apache License 2.0
234 stars 70 forks source link

When parsing, there is no way to get int value of an enum #7

Open kennberg opened 12 years ago

kennberg commented 12 years ago

Right now when I parse a message in node, the enum value is set to string. However, string is not an efficient representation of enum. It takes longer to compare, it takes more space in the database, etc.

Possible solutions:

  1. Provide a mapping from string to int.
  2. Set option to always return int for enums.
  3. Generate a simple module that contains constants for all the enums in the protobuf.

Solutions #2 + #3 are likely to generate the nicest and most efficient server-side code.

chrisdew commented 12 years ago

I've come across this myself. I like #2, but with the following options:

a) enums as ints b) enums as strings c) enums as objects of the form { int:13, string:"EACCES" }

chrisdew commented 12 years ago

I've done #3 for one enum:

var reasonToNum = createReasonToNum();

/*
 * create a reason text -> num lookup table
 */
function createReasonToNum() {
  var map = {};
  for (var i = 1; i < 255; i++) {
    try {
      var ad = ApplicationData.parse(ApplicationData.serialize({ reason: i }));
      map[ad.reason] = i;
    } catch (e) {
      // FIXME: be more discerning and eat only protobuf generated errors 
    }
  }
  return map;
}

kennberg commented 12 years ago

2 seems like a quick fix in C++ code. Do you have ideas on how to auto-generate the JS module for #3? Perhaps, it can be a part of the protobuf module that is generated.

Thanks for the loop idea. It probably makes sense to break on exception?

kennberg commented 12 years ago

Hey, I've created and open sourced a convenience wrapper for this. Maybe there is a path that we can merge it into this module? I don't mind.

https://github.com/kennberg/node-protobuf-wrapper

chrisdew commented 12 years ago

See #19 for another field type which needs some form of 'retrieval type parameterisation'.