From 46b77c4be6c0cbd336f4e4501b9722de6ce25666 Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Fri, 16 Jan 2009 22:34:40 +0000 Subject: [PATCH] THRIFT-224 Validate method should check that enum types are assigned valid values Each generated enumeration type will now have a VALID_VALUES Set as a static member that contains all the values of the enumeration. git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@735167 13f79535-47bb-0310-9956-ffa450edef68 --- compiler/cpp/src/generate/t_rb_generator.cc | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/compiler/cpp/src/generate/t_rb_generator.cc b/compiler/cpp/src/generate/t_rb_generator.cc index e3c3031f..83c69efe 100644 --- a/compiler/cpp/src/generate/t_rb_generator.cc +++ b/compiler/cpp/src/generate/t_rb_generator.cc @@ -297,6 +297,18 @@ void t_rb_generator::generate_enum(t_enum* tenum) { f_types_ << indent() << name << " = " << value << endl; } + + // Create a set with valid values for this enum + indent(f_types_) << "VALID_VALUES = Set.new(["; + bool first = true; + for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) { + // Populate the set + if ((*c_iter)->has_value()){ + first ? first = false: f_types_ << ", "; + f_types_ << capitalize((*c_iter)->get_name()); + } + } + f_types_ << "]).freeze" << endl; indent_down(); indent(f_types_) << @@ -1060,6 +1072,19 @@ void t_rb_generator::generate_rb_struct_required_validator(std::ofstream& out, } out << endl; } + } + + // if field is an enum, check that its value is valid + for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) { + t_field* field = (*f_iter); + + if (field->get_type()->is_enum()){ + indent(out) << "unless @" << field->get_name() << ".nil? || " << field->get_type()->get_name() << "::VALID_VALUES.include?(@" << field->get_name() << ")" << endl; + indent_up(); + indent(out) << "raise Thrift::ProtocolException.new(Thrift::ProtocolException::UNKNOWN, 'Invalid value of field " << field->get_name() << "!')" << endl; + indent_down(); + indent(out) << "end" << endl; + } } indent_down(); -- 2.17.1