Module: Cecil::Lang::Rust::Helpers

Defined in:
lib/cecil/lang/rust.rb

Constant Summary collapse

CHAR_TO_CUSTOM_ESCAPE_LITERAL =
{
  "\n" => '\n',
  "\r" => '\r',
  "\t" => '\t',
  "\0" => '\0',
  "\\" => "\\\\", # \ => \\
  '"' => '\\"'    # " => \"
}.freeze

Instance Method Summary collapse

Instance Method Details

#l(items) ⇒ String

Short for "list"; Accepts one or a list of strings and returns them joined with ", "

Parameters:

  • items (Array[#to_s], #to_s)

    One or a list of objects that respond to #to_s

Returns:

  • (String)

    The stringified inputs concatenated with ", "



17
# File 'lib/cecil/lang/rust.rb', line 17

def l(items) = Array(items).compact.join(", ")

#rchar(char) ⇒ Object

Escapes a character (string with one character) for use in a Rust string literal.

Examples:

rchar("\n") # => \n
rchar('"')  # => \"
rchar('😉') # => \u{1f609}


42
43
44
45
46
47
48
# File 'lib/cecil/lang/rust.rb', line 42

def rchar(char)
  CHAR_TO_CUSTOM_ESCAPE_LITERAL[char] ||
    case char
    when /^[ -~]$/ then char
    else unicode_escape(char)
    end
end

#rs(val) ⇒ Object

short for "rust value"; returns a Rust literal version of the input.

Currently handles strings, integers, floats, and booleans.

Examples:

`let name = $name;`[rs "Bob \"the Machine\" O\'Brian (Admin)"]
`let age = $age;`[rs 42]
`let friendliness = $friendliness;`[rs 9.9]
`let is_admin = $is_admin;`[rs true]

# outputs:
# let name = "Bob \"the Machine\" O\'Brian (Admin)";
# let age = 42;
# let friendliness = 9.9;
# let is_admin = true;


82
83
84
85
86
87
# File 'lib/cecil/lang/rust.rb', line 82

def rs(val)
  case val
  in String then %("#{s val}")
  in Integer | Float | true | false then val.to_s
  end
end

#s(val) ⇒ String

Short for "string content"; returns escaped version of the string that can be inserted into a string literal.

Useful for inserting data into a string or for outputting a string but using quotes to make it clear to the reader what the intended output will be.

Examples:

Inserting into a string literal

name = %q{Bob "the Machine" O'Brian}
`let admin = "$name (Admin)";`[s name]

# outputs:
# let admin = "Bob \"the Machine\" O\'Brian (Admin)";

Parameters:

  • val (#to_s)

    A string or any object that responds to #to_s

Returns:

  • (String)

    A JSON string without quotes



65
# File 'lib/cecil/lang/rust.rb', line 65

def s(val) = val.each_char.map { rchar(_1) }.join

#unicode_escape(str) ⇒ Object

Escapes string as unicode character literals



24
# File 'lib/cecil/lang/rust.rb', line 24

def unicode_escape(str) = str.each_codepoint.map { unicode_escape_codepoint(_1) }.join

#unicode_escape_codepoint(char_int) ⇒ Object

Escapes codepoint as unicode character literal See https://doc.rust-lang.org/reference/tokens.html#unicode-escapes



21
# File 'lib/cecil/lang/rust.rb', line 21

def unicode_escape_codepoint(char_int) = "\\u{#{char_int.to_s(16)}}"