After an evaluation, GNOME has moved from Bugzilla to GitLab. Learn more about GitLab.
No new issues can be reported in GNOME Bugzilla anymore.
To report an issue in a GNOME project, go to GNOME GitLab.
Do not go to GNOME Gitlab for: Bluefish, Doxygen, GnuCash, GStreamer, java-gnome, LDTP, NetworkManager, Tomboy.
Bug 595458 - Enhance enum to increase its usefulness
Enhance enum to increase its usefulness
Status: RESOLVED FIXED
Product: vala
Classification: Core
Component: Basic Types
0.7.x
Other Linux
: Normal enhancement
: ---
Assigned To: Vala maintainers
Vala maintainers
Depends on:
Blocks:
 
 
Reported: 2009-09-17 14:10 UTC by Michael Trausch
Modified: 2010-01-09 11:15 UTC
See Also:
GNOME target: ---
GNOME version: ---



Description Michael Trausch 2009-09-17 14:10:16 UTC
It is often nice to be able to take a value from an enumeration and output it in a program to the display (in a log file, or whatever).  So, say you have:

public enum AddressType {
  IPv4,
  IPv6
}

And you have this somewhere:

AddressType at = AddressType.IPv4;
stderr.printf("Using address type %d.\n", at);

This would display "Using address type 0." on stderr.  However, it would be nice and more useful to do replace the above printf with this:

stderr.printf("Using address type %s.\n", at);

Or, if the implicit conversion is undesired:

stderr.printf("Using address type %s.\n", at.to_string());

That would then show "Using address type IPv4." or something similar and just as meaningful, even if the case is altered due to the transformation into C code and C coding conventions.

It seems that this *should* be possible, given that GEnum is used, and a GEnumValue (when the enum type is known) should easily resolve to a type.  It would also make it possible to print "flags" type enumerations in a meaningful way, though that would be more difficult, I expect.
Comment 1 Michael 'Mickey' Lauer 2009-10-15 23:08:42 UTC
Try that:

public string enumToString( Type enum_type, int value )
{
    EnumClass ec = (EnumClass) enum_type.class_ref();
    unowned EnumValue ev = ec.get_value( value );
    return ev == null ? "Unknown Enum value for %s: %i".printf( enum_type.name(), value ) : ev.value_name;
}

I'd love to see it Vala integrated, but Jürg seems to have reservations.
Comment 2 Michael 'Mickey' Lauer 2009-10-15 23:09:14 UTC
(as to_string() for an enum, of course, not as a seperate top-level-function)
Comment 3 Henrik /KaarPoSoft 2009-12-26 21:05:56 UTC
For whatever it is worth:

I completely agree with Mickey above:
It would be great to be able to write

enum X { ... };
X x = ...;
log(..., @"... $x ...");

which would be possible if an enum would have an implicit to_string "method".
Comment 4 Jürg Billeter 2010-01-09 11:15:12 UTC
commit 1fbdecd6d5bc61c6347fc1718368a0fbbafec0c9
Author: Jürg Billeter <j@bitron.ch>
Date:   Sat Jan 9 12:12:22 2010 +0100

    Support to_string for enums