Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust: Enum names not only numbers #202

Merged
merged 2 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/xdrgen/ast/definitions/enum_member.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ class EnumMember < Base

def name_short
prefix = find_common_prefix(enum.members.map(&:name))
name.delete_prefix(prefix)
short = name.delete_prefix(prefix)
# Prefix the name with the first letter of the prefix if the name begins
# with a number, since in most languages identifiers cannot begin with
# numbers.
short = "#{prefix.first}#{short}" if /\A\d+/ === short
short
end

def value
Expand Down Expand Up @@ -46,4 +51,4 @@ def defined_value
end
end
end
end
end
7 changes: 6 additions & 1 deletion lib/xdrgen/ast/definitions/union_arm_case.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ def value_s

def name_short
prefix = find_common_prefix(union.discriminant_type.members.map(&:name))
value.name.delete_prefix(prefix)
short = value.name.delete_prefix(prefix)
# Prefix the name with the first letter of the prefix if the name begins
# with a number, since in most languages identifiers cannot begin with
# numbers.
short = "#{prefix.first}#{short}" if /\A\d+/ === short
short
end
end
end
Expand Down
8 changes: 7 additions & 1 deletion spec/fixtures/generator/enum.x
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,10 @@ enum Color2 {
RED2=RED,
GREEN2=1,
BLUE2=2
};
};

enum Color3 {
RED_1=1,
RED_2_TWO=2,
RED_3=3
};
17 changes: 17 additions & 0 deletions spec/output/generator_spec_elixir/enum.x/MyXDR_generated.ex
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,21 @@ defmodule MyXDR do
blue2: 2
)

comment ~S"""
=== xdr source ============================================================

enum Color3 {
RED_1=1,
RED_2_TWO=2,
RED_3=3
};

===========================================================================
"""
define_type("Color3", Enum,
red1: 1,
red2_two: 2,
red3: 3
)

end
87 changes: 86 additions & 1 deletion spec/output/generator_spec_go/enum.x/MyXDR_generated.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (

// XdrFilesSHA256 is the SHA256 hashes of source files.
var XdrFilesSHA256 = map[string]string{
"spec/fixtures/generator/enum.x": "35cf5e97e2057039640ed260e8b38bb2733a3c3ca8529c93877bdec02a999d7f",
"spec/fixtures/generator/enum.x": "f764c2a2d349765e611f686e9d416b7f576ea881154d069355a2e75c898daf58",
}

var ErrMaxDecodingDepthReached = errors.New("maximum decoding depth reached")
Expand Down Expand Up @@ -358,4 +358,89 @@ func (s Color2) xdrType() {}

var _ xdrType = (*Color2)(nil)

// Color3 is an XDR Enum defines as:
//
// enum Color3 {
// RED_1=1,
// RED_2_TWO=2,
// RED_3=3
// };
//
type Color3 int32
const (
Color3Red1 Color3 = 1
Color3Red2Two Color3 = 2
Color3Red3 Color3 = 3
)
var color3Map = map[int32]string{
1: "Color3Red1",
2: "Color3Red2Two",
3: "Color3Red3",
}

// ValidEnum validates a proposed value for this enum. Implements
// the Enum interface for Color3
func (e Color3) ValidEnum(v int32) bool {
_, ok := color3Map[v]
return ok
}
// String returns the name of `e`
func (e Color3) String() string {
name, _ := color3Map[int32(e)]
return name
}

// EncodeTo encodes this value using the Encoder.
func (e Color3) EncodeTo(enc *xdr.Encoder) error {
if _, ok := color3Map[int32(e)]; !ok {
return fmt.Errorf("'%d' is not a valid Color3 enum value", e)
}
_, err := enc.EncodeInt(int32(e))
return err
}
var _ decoderFrom = (*Color3)(nil)
// DecodeFrom decodes this value using the Decoder.
func (e *Color3) DecodeFrom(d *xdr.Decoder, maxDepth uint) (int, error) {
if maxDepth == 0 {
return 0, fmt.Errorf("decoding Color3: %w", ErrMaxDecodingDepthReached)
}
maxDepth -= 1
v, n, err := d.DecodeInt()
if err != nil {
return n, fmt.Errorf("decoding Color3: %w", err)
}
if _, ok := color3Map[v]; !ok {
return n, fmt.Errorf("'%d' is not a valid Color3 enum value", v)
}
*e = Color3(v)
return n, nil
}
// MarshalBinary implements encoding.BinaryMarshaler.
func (s Color3) MarshalBinary() ([]byte, error) {
b := bytes.Buffer{}
e := xdr.NewEncoder(&b)
err := s.EncodeTo(e)
return b.Bytes(), err
}

// UnmarshalBinary implements encoding.BinaryUnmarshaler.
func (s *Color3) UnmarshalBinary(inp []byte) error {
r := bytes.NewReader(inp)
o := xdr.DefaultDecodeOptions
o.MaxInputLen = len(inp)
d := xdr.NewDecoderWithOptions(r, o)
_, err := s.DecodeFrom(d, o.MaxDepth)
return err
}

var (
_ encoding.BinaryMarshaler = (*Color3)(nil)
_ encoding.BinaryUnmarshaler = (*Color3)(nil)
)

// xdrType signals that this type represents XDR values defined by this package.
func (s Color3) xdrType() {}

var _ xdrType = (*Color3)(nil)

var fmtTest = fmt.Sprint("this is a dummy usage of fmt")
61 changes: 61 additions & 0 deletions spec/output/generator_spec_java/enum.x/Color3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten

package MyXDR;

import java.io.IOException;

import org.stellar.sdk.Base64Factory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
* Color3's original definition in the XDR file is:
* <pre>
* enum Color3 {
* RED_1=1,
* RED_2_TWO=2,
* RED_3=3
* };
* </pre>
*/
public enum Color3 implements XdrElement {
RED_1(1),
RED_2_TWO(2),
RED_3(3);

private final int value;

Color3(int value) {
this.value = value;
}

public int getValue() {
return value;
}

public static Color3 decode(XdrDataInputStream stream) throws IOException {
int value = stream.readInt();
switch (value) {
case 1: return RED_1;
case 2: return RED_2_TWO;
case 3: return RED_3;
default:
throw new IllegalArgumentException("Unknown enum value: " + value);
}
}

public void encode(XdrDataOutputStream stream) throws IOException {
stream.writeInt(value);
}
public static Color3 fromXdrBase64(String xdr) throws IOException {
byte[] bytes = Base64Factory.getInstance().decode(xdr);
return fromXdrByteArray(bytes);
}

public static Color3 fromXdrByteArray(byte[] xdr) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xdr);
XdrDataInputStream xdrDataInputStream = new XdrDataInputStream(byteArrayInputStream);
return decode(xdrDataInputStream);
}
}
15 changes: 15 additions & 0 deletions spec/output/generator_spec_javascript/enum.x/MyXDR_generated.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,5 +82,20 @@ xdr.enum("Color2", {
blue2: 2,
});

// === xdr source ============================================================
//
// enum Color3 {
// RED_1=1,
// RED_2_TWO=2,
// RED_3=3
// };
//
// ===========================================================================
xdr.enum("Color3", {
red1: 1,
red2Two: 2,
red3: 3,
});

});
export default types;
1 change: 1 addition & 0 deletions spec/output/generator_spec_python/enum.x/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
from .message_type import MessageType
from .color import Color
from .color2 import Color2
from .color3 import Color3
50 changes: 50 additions & 0 deletions spec/output/generator_spec_python/enum.x/color3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
from __future__ import annotations

import base64
from enum import IntEnum
from typing import List, Optional, TYPE_CHECKING
from xdrlib3 import Packer, Unpacker
from .base import Integer, UnsignedInteger, Float, Double, Hyper, UnsignedHyper, Boolean, String, Opaque
from .constants import *

__all__ = ['Color3']
class Color3(IntEnum):
"""
XDR Source Code::

enum Color3 {
RED_1=1,
RED_2_TWO=2,
RED_3=3
};
"""
RED_1 = 1
RED_2_TWO = 2
RED_3 = 3
def pack(self, packer: Packer) -> None:
packer.pack_int(self.value)

@classmethod
def unpack(cls, unpacker: Unpacker) -> Color3:
value = unpacker.unpack_int()
return cls(value)
def to_xdr_bytes(self) -> bytes:
packer = Packer()
self.pack(packer)
return packer.get_buffer()

@classmethod
def from_xdr_bytes(cls, xdr: bytes) -> Color3:
unpacker = Unpacker(xdr)
return cls.unpack(unpacker)

def to_xdr(self) -> str:
xdr_bytes = self.to_xdr_bytes()
return base64.b64encode(xdr_bytes).decode()

@classmethod
def from_xdr(cls, xdr: str) -> Color3:
xdr_bytes = base64.b64decode(xdr.encode())
return cls.from_xdr_bytes(xdr_bytes)
1 change: 1 addition & 0 deletions spec/output/generator_spec_ruby/enum.x/MyXDR.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
autoload :MessageType
autoload :Color
autoload :Color2
autoload :Color3
21 changes: 21 additions & 0 deletions spec/output/generator_spec_ruby/enum.x/color3.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# This code was automatically generated using xdrgen
# DO NOT EDIT or your changes may be overwritten

require 'xdr'

# === xdr source ============================================================
#
# enum Color3 {
# RED_1=1,
# RED_2_TWO=2,
# RED_3=3
# };
#
# ===========================================================================
class Color3 < XDR::Enum
member :red_1, 1
member :red_2_two, 2
member :red_3, 3

seal
end
Loading
Loading