Text

abstract class Text

High-level abstraction for all text representations

Inheritance

dep_class_core__text__abstract_text__TextObjectObjectSerializableSerializableSerializable->ObjectComparableComparableComparable->ObjectCloneableCloneableCloneable->ObjectPatternPatternPattern->ObjectWritableWritableWritable->ObjectSendableSendableSendable->ObjectDirectSerializableDirectSerializableDirectSerializable->SerializableTextTextText->ComparableText->CloneableText->PatternText->WritableText->SendableText->DirectSerializableFlatTextFlatTextFlatText->TextStringStringString->TextBufferBufferBuffer->TextFlatStringFlatStringFlatString->FlatTextFlatString->StringFlatBufferFlatBufferFlatBuffer->FlatTextFlatBuffer->Buffer

Parents

  • Cloneable: Something that can be cloned
  • Comparable: The ancestor of class where objects are in a total order.
  • DirectSerializable: Instances of this class are not delayed and instead serialized immediately
  • Pattern: Patterns are abstract string motifs (include String and Char).
  • Sendable: Something sendable directly and efficiently over MPI
  • Writable: Things that can be efficienlty written to a Writer

Ancestors

  • Object: The root of the class hierarchy.
  • Serializable: Instances of this class can be passed to Serializer::serialize

Children

  • Buffer: A mutable sequence of characters.
  • FlatText: All kinds of array-based text representations.
  • String: Immutable sequence of characters.

Descendants

Constructors

Concerns

  • core: Nit common library of core classes and methods
    • text: All the classes and methods related to the manipulation of text entities
    • bytes: Services for byte streams and arrays
    • numeric: Advanced services for Numeric types
    • re: Regular expression support for all services based on Pattern
    • stream: Input and output streams of characters
    • file: File manipulations (create, read, write, etc.)
  • base64: Offers the base 64 encoding and decoding algorithms
    • base64: Offers the base 64 encoding and decoding algorithms
  • cpp: Services for compatibility with C++ code and libraries
    • cpp: Services for compatibility with C++ code and libraries
  • emscripten: Platform for the emscripten framework
    • emscripten: Platform for the emscripten framework
  • md5: Native MD5 digest implementation as Text::md5
    • md5: Native MD5 digest implementation as Text::md5
  • ropes_debug: Exposes methods for debugging ropes when needed.
    • ropes_debug: Exposes methods for debugging ropes when needed.
  • sha1: Provides methods to compute the SHA1 hash of a String
    • sha1: Provides methods to compute the SHA1 hash of a String
  • crypto: Mix of all things cryptography-related
  • gmp: Multi precision integer and rational number using gmp lib
    • gmp: Multi precision integer and rational number using gmp lib
  • sqlite3: Services to manipulate a Sqlite3 database
    • sqlite3: Services to manipulate a Sqlite3 database
  • privileges: Process privileges management utilities
    • privileges: Process privileges management utilities
  • cocoa: Cocoa API, the development layer of OS X
    • foundation: The Foundation Kit provides basic Objective-C classes and structures
  • java: Supporting services for the FFI with Java and to access Java libraries
    • ffi_support: Core supporting services for the FFI with Java
  • crapto: Cryptographic attacks and utilities.
    • english_utils: English language utilities for cryptographic purposes.
  • serialization: Abstract serialization services
  • sexp: S-Expression parsing facilities
    • sexp: S-Expression parsing facilities
  • dom: Easy XML DOM parser
    • parser: XML DOM-parsing facilities
  • json: read and write JSON formatted text
    • serialization_write: Services to write Nit objects to JSON strings: serialize_to_json and JsonSerializer
    • static: Static interface to read Nit objects from JSON strings
    • dynamic: Dynamic interface to read JSON strings.
    • serialization_read: Services to read JSON: from_json_string and JsonDeserializer
  • app: app.nit, a framework for portable applications
    • ui: Portable UI controls for mobiles apps
  • ios: iOS support for app.nit
    • ui: Implementation of app::ui for iOS
      • ui: Implementation of app::ui for iOS
  • linux: Implementation of app.nit for the Linux platform
    • ui: Implementation of the app.nit UI module for GNU/Linux
  • mpi: Implementation of the Message Passing Interface protocol by wrapping OpenMPI
    • mpi: Implementation of the Message Passing Interface protocol by wrapping OpenMPI
  • msgpack: MessagePack, an efficient binary serialization format
  • gamnit: Portable game and multimedia framework for Nit
    • bmfont: Parse Angel Code BMFont format and draw text
  • android: Android platform support and APIs
    • ui: Views and services to use the Android native user interface
      • ui: Views and services to use the Android native user interface

in core::text::abstract_text

redef type SELF

Type of this instance, automatically specialized in every class

A common use case of the virtual type SELF is to type an attribute and store another instance of the same type as self. It can also be used as as return type to a method producing a copy of self or returning an instance expected to be the exact same type as self.

This virtual type must be used with caution as it can hinder specialization. In fact, it imposes strict restrictions on all sub-classes and their usage. For example, using SELF as a return type of a method foo forces all subclasses to ensure that foo returns the correct and updated type. A dangerous usage take the form of a method typed by SELF which creates and returns a new instance. If not correctly specialized, this method would break when invoked on a sub-class.

A general rule for safe usage of SELF is to ensure that inputs typed SELF are stored in attributes typed SELF and returned by methods typed SELF, pretty much the same things as you would do with parameter types.

redef fun ==(o)

Equality of text

Two pieces of text are equals if thez have the same characters in the same order.

assert "hello" == "hello"
assert "hello" != "HELLO"
assert "hello" == "hel"+"lo"

Things that are not Text are not equal.

assert "9" != '9'
assert "9" != ['9']
assert "9" != 9

assert "9".chars.first == '9'   # equality of Char
assert "9".chars       == ['9'] # equality of Sequence
assert "9".to_i        == 9

fun capitalized(keep_upper: nullable Bool): SELFTYPE

Returns a capitalized self

Letters that follow a letter are lowercased Letters that follow a non-letter are upcased.

If keep_upper = true, already uppercase letters are not lowercased.

SEE : Char::is_letter for the definition of letter.

assert "jAVASCRIPT".capitalized == "Javascript"
assert "i am root".capitalized == "I Am Root"
assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"

fun chomp: SELFTYPE

Returns self removed from its last line terminator (if any).

assert "Hello\n".chomp == "Hello"
assert "Hello".chomp   == "Hello"

assert "\n".chomp == ""
assert "".chomp   == ""

Line terminators are "\n", "\r\n" and "\r". A single line terminator, the last one, is removed.

assert "\r\n".chomp     == ""
assert "\r\n\n".chomp   == "\r\n"
assert "\r\n\r\n".chomp == "\r\n"
assert "\r\n\r".chomp   == "\r\n"

Note: unlike with most IO methods like Reader::read_line, a single \r is considered here to be a line terminator and will be removed.

fun escape_to_c: String

Escape " \ ', trigraphs and non printable characters using the rules of literal C strings and characters

assert "abAB12<>&".escape_to_c       == "abAB12<>&"
assert "\n\"'\\".escape_to_c         == "\\n\\\"\\'\\\\"
assert "allo???!".escape_to_c        == "allo??\\?!"
assert "??=??/??'??(??)".escape_to_c == "?\\?=?\\?/??\\'?\\?(?\\?)"
assert "??!??<??>??-".escape_to_c    == "?\\?!?\\?<?\\?>?\\?-"

Most non-printable characters (bellow ASCII 32) are escaped to an octal form \nnn. Three digits are always used to avoid following digits to be interpreted as an element of the octal sequence.

assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "

The exceptions are the common \t and \n.

fun format(args: Object...): String

Format self by replacing each %n with the nth item of args

The character % followed by something other than a number are left as is. To represent a % followed by a number, double the %, as in %%7.

assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"

fun from_percent_encoding: String

Decode self from percent (or URL) encoding to a clear string

Invalid '%' are not decoded.

assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
assert "incomplete %".from_percent_encoding == "incomplete %"
assert "invalid % usage".from_percent_encoding == "invalid % usage"
assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
assert "%1 %A %C3%A9A9".from_percent_encoding == "%1 %A éA9"

fun has_substring(str: String, pos: Int): Bool

Does self have a substring str starting from position pos?

assert "abcd".has_substring("bc",1)      ==  true
assert "abcd".has_substring("bc",2)      ==  false

Returns true iff all characters of str are presents at the expected index in self. The first character of str being at pos, the second character being at pos+1 and so on...

This means that all characters of str need to be inside self.

assert "abcd".has_substring("xab", -1)         == false
assert "abcd".has_substring("cdx", 2)          == false

And that the empty string is always a valid substring.

assert "abcd".has_substring("", 2)             == true
assert "abcd".has_substring("", 200)           == true

redef fun hash

The hash code of the object.

The hash code is used in many data-structures and algorithms to identify objects that might be equal. Therefore, the precise semantic of hash is highly linked with the semantic of == and the only law of hash is that a == b implies a.hash == b.hash.

assert (1+1).hash == 2.hash
assert 1.to_s.hash == "1".hash

hash (like ==) might not be constant on some objects over time because of their evolution.

var a = [1]
var b = [1]
var c = [1,2]
assert a.hash == b.hash
a.add 2
assert a.hash == c.hash

A specific redefinition of == should usually be associated with a specific redefinition of hash. Note that, unfortunately, a correct definition of hash that is lawful with == is sometime tricky and a cause of bugs.

Without redefinition, hash is based on the object_id of the instance.

fun is_numeric: Bool

Is this string in a valid numeric format compatible with to_f?

assert "123".is_numeric  == true
assert "1.2".is_numeric  == true
assert "-1.2".is_numeric == true
assert "-1.23e-2".is_numeric == true
assert "1..2".is_numeric == false
assert "".is_numeric     == false

fun justify(length: Int, left: Float, char: nullable Char): String

Justify self in a space of length

left is the space ratio on the left side.

  • 0.0 for left-justified (no space at the left)
  • 1.0 for right-justified (all spaces at the left)
  • 0.5 for centered (half the spaces at the left)

char, or ' ' by default, is repeated to pad the empty space.

Examples

assert "hello".justify(10, 0.0)  == "hello     "
assert "hello".justify(10, 1.0)  == "     hello"
assert "hello".justify(10, 0.5)  == "  hello   "
assert "hello".justify(10, 0.5, '.') == "..hello..."

If length is not enough, self is returned as is.

assert "hello".justify(2, 0.0)   == "hello"

REQUIRE: left >= 0.0 and left <= 1.0

ENSURE: self.length <= length implies result.length == length

ENSURE: self.length >= length implies result == self

abstract fun substring(from: Int, count: Int): SELFTYPE

Create a substring.

assert "abcd".substring(1, 2)      ==  "bc"
assert "abcd".substring(-1, 2)     ==  "a"
assert "abcd".substring(1, 0)      ==  ""
assert "abcd".substring(2, 5)      ==  "cd"
assert "あいうえお".substring(1,3) ==  "いうえ"

A from index < 0 will be replaced by 0. Unless a count value is > 0 at the same time. In this case, from += count and count -= from.

abstract fun to_camel_case: SELFTYPE

Takes a snake case self and converts it to camel case

assert "random_method_id".to_camel_case == "randomMethodId"

If the identifier is prefixed by an underscore, the underscore is ignored

assert "_private_field".to_camel_case == "_privateField"

If self is upper, it is returned unchanged

assert "RANDOM_ID".to_camel_case == "RANDOM_ID"

If there are several consecutive underscores, they are considered as a single one

assert "random__method_id".to_camel_case == "randomMethodId"

fun to_cmangle: String

Mangle a string to be a unique string only made of alphanumeric characters and underscores.

This method is injective (two different inputs never produce the same output) and the returned string always respect the following rules:

  • Contains only US-ASCII letters, digits and underscores.

  • Never starts with a digit.

  • Never ends with an underscore.

  • Never contains two contiguous underscores.

    assert "42_is/The answer!".to_cmangle == "52d2_is_47dThe_32danswer_33d" assert "".to_cmangle == "95d_95d" assert "_d".to_cmangle == "95d_d" assert "d".to_cmangle == "d_95d" assert "42".to_cmangle == "_95d42" assert "foo".to_cmangle == "foo" assert "".to_cmangle == ""

abstract fun to_snake_case: SELFTYPE

Takes a camel case self and converts it to snake case

assert "randomMethodId".to_snake_case == "random_method_id"

The rules are the following:

An uppercase is always converted to a lowercase

assert "HELLO_WORLD".to_snake_case == "hello_world"

An uppercase that follows a lowercase is prefixed with an underscore

assert "HelloTheWORLD".to_snake_case == "hello_the_world"

An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore

assert "HelloTHEWorld".to_snake_case == "hello_the_world"

All other characters are kept as is; self does not need to be a proper CamelCased string.

assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="

in core::text::string_search

redef fun search_in(s, from)

Search self into s from a certain position.

Return null if not found.

assert 'l'.search_in("hello world", 0).from  == 2
assert 'l'.search_in("hello world", 3).from  == 3
assert 'z'.search_in("hello world", 0)       == null

If only the index of the first character if required, see search_index_in.

Note: Is used by String::search, String::search_from, and others.

redef fun search_index_in(s, from)

Search self into s from a certain position.

Return the position of the first character of the matching section. Return -1 if not found.

assert 'l'.search_index_in("hello world", 0)  == 2
assert 'l'.search_index_in("hello world", 3)  == 3
assert 'z'.search_index_in("hello world", 0)  == -1

This method is usually faster than search_in if what is

required is only the index.

Note: in most implementation, search_in is implemented with this method.

fun search_last(t: Text): nullable Match

Search the last occurence of the text t.

assert "bob".search_last("b").from == 2
assert "bob".search_last("bo").from == 0
assert "bob".search_last("ob").from == 1
assert "bobob".search_last("ob").from == 3
assert "bobbob".search_last("bb").from == 2
assert "bobbob".search_last("bob").from == 3
assert "bob".search_last("z") == null
assert "".search_last("b") == null

in core::text::fixed_ints_text

in core::bytes

fun binarydigest_to_bytes: Bytes

Return a Bytes by reading 0 and 1.

assert "1010101100001101".binarydigest_to_bytes.hexdigest == "AB0D"

Note that characters that are neither 0 or 1 are just ignored.

assert "a1B01 010\n1100あ001101".binarydigest_to_bytes.hexdigest == "AB0D"
assert "hello".binarydigest_to_bytes.is_empty

When the number of bits is not divisible by 8, then leading 0 are implicitly considered to fill the left byte (the most significant one).

assert "1".binarydigest_to_bytes.hexdigest == "01"
assert "1111111".binarydigest_to_bytes.hexdigest == "7F"
assert "1000110100".binarydigest_to_bytes.hexdigest == "0234"

Bytes::binarydigest is a loosely reverse method since its results contain only 1 and 0 by blocks of 8.

assert "1010101100001101".binarydigest_to_bytes.binarydigest == "1010101100001101"
assert "1".binarydigest_to_bytes.binarydigest == "00000001"

fun hexdigest_to_bytes: Bytes

Returns a new Bytes instance with the digest as content

assert "0B1F4D".hexdigest_to_bytes == [0x0Bu8, 0x1Fu8, 0x4Du8]
assert "0B1F4D".hexdigest_to_bytes.hexdigest == "0B1F4D"

Characters that are not hexadecimal digits are ignored.

assert "z0B1 F4\nD".hexdigest_to_bytes.hexdigest == "0B1F4D"
assert "\\x0b1 \\xf4d".hexdigest_to_bytes.hexdigest == "0B1F4D"

When the number of hexadecimal digit is not even, then a leading 0 is implicitly considered to fill the left byte (the most significant one).

assert "1".hexdigest_to_bytes.hexdigest == "01"
assert "FFF".hexdigest_to_bytes.hexdigest == "0FFF"

Bytes::hexdigest is a loosely reverse method since its results contain only pairs of uppercase hexadecimal digits.

assert "ABCD".hexdigest_to_bytes.hexdigest == "ABCD"
assert "a b c".hexdigest_to_bytes.hexdigest == "0ABC"

fun unescape_to_bytes: Bytes

Return a Bytes instance where Nit escape sequences are transformed.

assert "B\\n\\x41\\u0103D3".unescape_to_bytes.hexdigest == "420A41F0908F93"

Bytes::chexdigest is a loosely reverse methods since its result is only made of "\x??" escape sequences.

assert "\\x41\\x42\\x43".unescape_to_bytes.chexdigest == "\\x41\\x42\\x43"
assert "B\\n\\x41\\u0103D3".unescape_to_bytes.chexdigest == "\\x42\\x0A\\x41\\xF0\\x90\\x8F\\x93"

in core::numeric

in core::re

in core::stream

in core::file

fun /(path: Text): String

Alias for join_path

assert "hello" / "world"      ==  "hello/world"
assert "hel/lo" / "wor/ld"    ==  "hel/lo/wor/ld"
assert "" / "world"           ==  "world"
assert "/hello" / "/world"    ==  "/world"

This operator is quite useful for chaining changes of path. The next one being relative to the previous one.

var a = "foo"
var b = "/bar"
var c = "baz/foobar"
assert a/b/c == "/bar/baz/foobar"

fun basename(extension: nullable String): String

Extract the basename of a path and strip the extension

The extension is stripped only if extension != null.

assert "/path/to/a_file.ext".basename(".ext")     == "a_file"
assert "path/to/a_file.ext".basename(".ext")      == "a_file"
assert "path/to/a_file.ext".basename              == "a_file.ext"
assert "path/to".basename(".ext")                 == "to"
assert "path/to/".basename(".ext")                == "to"
assert "path/to".basename                         == "to"
assert "path".basename                            == "path"
assert "/path".basename                           == "path"
assert "/".basename                               == "/"
assert "".basename                                == ""

On Windows, '' are replaced by '/':

assert "C:\\path\\to\\a_file.ext".basename(".ext")    == "a_file"
assert "C:\\".basename                                == "C:"

fun chdir: nullable Error

Change the current working directory

"/etc".chdir
assert getcwd == "/etc"
"..".chdir
assert getcwd == "/"

Return an error object in case of error.

assert "/etc".chdir == null
assert "/fail/does no/exist".chdir != null
assert getcwd == "/etc"

fun dirname: String

Extract the dirname of a path

assert "/path/to/a_file.ext".dirname         == "/path/to"
assert "path/to/a_file.ext".dirname          == "path/to"
assert "path/to".dirname                     == "path"
assert "path/to/".dirname                    == "path"
assert "path".dirname                        == "."
assert "/path".dirname                       == "/"
assert "/".dirname                           == "/"
assert "".dirname                            == "."

On Windows, '' are replaced by '/':

assert "C:\\path\\to\\a_file.ext".dirname        == "C:/path/to"
assert "C:\\file".dirname                        == "C:"

fun file_extension: nullable String

Return right-most extension (without the dot)

Only the last extension is returned. There is no special case for combined extensions.

assert "file.txt".file_extension      == "txt"
assert "file.tar.gz".file_extension   == "gz"

For file without extension, null is returned. Hoever, for trailing dot, "" is returned.

assert "file".file_extension          == null
assert "file.".file_extension         == ""

The starting dot of hidden files is never considered.

assert ".file.txt".file_extension     == "txt"
assert ".file".file_extension         == null

fun files: Array[String]

Returns entries contained within the directory represented by self.

var files = "/etc".files
assert files.has("issue")

Returns an empty array in case of error

files = "/etc/issue".files
assert files.is_empty

TODO find a better way to handle errors and to give them back to the user.

fun join_path(path: Text): String

Correctly join two path using the directory separator.

Using a standard "{self}/{path}" does not work in the following cases:

  • self is empty.
  • path starts with '/'.

This method ensures that the join is valid.

assert "hello".join_path("world")   == "hello/world"
assert "hel/lo".join_path("wor/ld") == "hel/lo/wor/ld"
assert "".join_path("world")        == "world"
assert "hello".join_path("/world")  == "/world"
assert "hello/".join_path("world")  == "hello/world"
assert "hello/".join_path("/world") == "/world"

Note: You may want to use simplify_path on the result.

Note: This method works only with POSIX paths.

fun mkdir(mode: nullable Int): nullable Error

Create a directory (and all intermediate directories if needed)

The optional mode parameter specifies the permissions of the directory, the default value is 0o777.

Return an error object in case of error.

assert "/etc/".mkdir != null

fun relpath(dest: String): String

Returns the relative path needed to go from self to dest.

assert "/foo/bar".relpath("/foo/baz") == "../baz"
assert "/foo/bar".relpath("/baz/bar") == "../../baz/bar"

If self or dest is relative, they are considered relatively to getcwd.

In some cases, the result is still independent of the current directory:

assert "foo/bar".relpath("..") == "../../.."

In other cases, parts of the current directory may be exhibited:

var p = "../foo/bar".relpath("baz")
var c = getcwd.basename
assert p == "../../{c}/baz"

For path resolution independent of the current directory (eg. for paths in URL), or to use an other starting directory than the current directory, just force absolute paths:

var start = "/a/b/c/d"
var p2 = (start/"../foo/bar").relpath(start/"baz")
assert p2 == "../../d/baz"

Neither self or dest has to be real paths or to exist in directories since the resolution is only done with string manipulations and without any access to the underlying file system.

If self and dest are the same directory, the empty string is returned:

assert "foo".relpath("foo") == ""
assert "foo/../bar".relpath("bar") == ""

The empty string and "." designate both the current directory:

assert "".relpath("foo/bar")  == "foo/bar"
assert ".".relpath("foo/bar") == "foo/bar"
assert "foo/bar".relpath("")  == "../.."
assert "/" + "/".relpath(".") == getcwd

fun rmdir: nullable Error

Delete a directory and all of its content, return true on success

Does not go through symbolic links and may get stuck in a cycle if there is a cycle in the filesystem.

Return an error object in case of error.

assert "/fail/does not/exist".rmdir != null

fun simplify_path: String

Simplify a file path by remove useless ., removing //, and resolving ..

  • .. are not resolved if they start the path
  • starting . is simplified unless the path is empty
  • starting / is not removed
  • trailing / is removed

Note that the method only work on the string:

  • no I/O access is performed
  • the validity of the path is not checked
assert "some/./complex/../../path/from/../to/a////file//".simplify_path      ==  "path/to/a/file"
assert "../dir/file".simplify_path       ==  "../dir/file"
assert "dir/../../".simplify_path        ==  ".."
assert "dir/..".simplify_path            ==  "."
assert "//absolute//path/".simplify_path ==  "/absolute/path"
assert "//absolute//../".simplify_path   ==  "/"
assert "/".simplify_path                 == "/"
assert "../".simplify_path               == ".."
assert "./".simplify_path                == "."
assert "././././././".simplify_path      == "."
assert "./../dir".simplify_path        == "../dir"
assert "./dir".simplify_path               == "dir"

On Windows, '' are replaced by '/':

assert "C:\\some\\.\\complex\\../../path/to/a_file.ext".simplify_path == "C:/path/to/a_file.ext"
assert "C:\\".simplify_path              == "C:"

fun strip_extension(extension: nullable String): String

Remove the trailing extension.

extension usually starts with a dot but could be anything.

assert "file.txt".strip_extension(".txt")   == "file"
assert "file.txt".strip_extension("le.txt") == "fi"
assert "file.txt".strip_extension("xt")     == "file.t"

If extension == null, the rightmost extension is stripped, including the last dot.

assert "file.txt".strip_extension           == "file"

If extension is not present, self is returned unmodified.

assert "file.txt".strip_extension(".tar.gz")  == "file.txt"

fun to_program_name: String

Convert the path (self) to a program name.

Ensure the path (self) will be treated as-is by POSIX shells when it is

used as a program name. In order to do that, prepend ./ if needed.

assert "foo".to_program_name == "./foo"
assert "/foo".to_program_name == "/foo"
assert "".to_program_name == "./"

in base64::base64

in cpp::cpp

in emscripten::emscripten

in md5::md5

fun md5: String

MD5 digest of self

assert "".md5 == "d41d8cd98f00b204e9800998ecf8427e"
assert "a".md5 == "0cc175b9c0f1b6a831c399e269772661"
assert "abc".md5 == "900150983cd24fb0d6963f7d28e17f72"

in ropes_debug::ropes_debug

in sha1::sha1

fun is_sha1_digest: Bool

Is self a SHA-1 hexdigest?

assert "2FD4E1C67A2D28FCED849EE1BB76E7391B93EB12".is_sha1_digest
assert not "Not a digest".is_sha1_digest
assert not "2FD4E1C67A2D28FCED849EE1B76E7391B93EB12".is_sha1_digest
assert not "2FD4E1C67A2D28FCED849EE1UB76E7391B93EB12".is_sha1_digest

fun sha1: Bytes

Computes the SHA1 of the receiver

Returns a digest of 20 bytes as a CString, note that all the characters are not necessarily ASCII. If you want the hex string version of the digest, use sha1_hexdigest.

import base64
assert "The quick brown fox jumps over the lazy dog".sha1 == [0x2Fu8, 0xD4u8, 0xE1u8, 0xC6u8, 0x7Au8, 0x2Du8, 0x28u8, 0xFCu8, 0xEDu8, 0x84u8, 0x9Eu8, 0xE1u8, 0xBBu8, 0x76u8, 0xE7u8, 0x39u8, 0x1Bu8, 0x93u8, 0xEBu8, 0x12u8]

in crypto::basic_ciphers

fun railfence(depth: Int): Text

Returns a rail-fence cipher from self with depth rails

Rail works by drawing a zig-zag pattern on depth rails.

Say we have "fuckingbehemoth".railfence(4)

This happens in-memory:

f.....g.....o..
.u...n.b...m.t.
..c.i...e.e...h
...k.....h.....

Therefore, yielding the ciphertext : "fgounbmtcieehkh"

assert "fuckingbehemoth".railfence(4) == "fgounbmtcieehkh"

fun rot(x: Int): Text

Performs a Rotation of x on each letter of self

Works by replacing every character in self by its rotated char.

Say we have a rotation of 3 (Caesar rotation, for culture) for a string : "aybabtu"

a, rotated by 3 becomes d y, rotated by 3 becomes b b, rotated by 3 becomes e t, rotated by 3 becomes w u, rotated by 3 becomes x

We then replace every letter in our original string by their rotated representations, therefore yielding : "dbedewx"

assert "All your base are belong to us".rot(13) == "Nyy lbhe onfr ner orybat gb hf"
assert "This is no moon.".rot(4).rot(22) == "This is no moon."

NOTE : Works on letters only NOTE : This cipher is symmetrically decrypted with an x of 26-x

in gmp::gmp

fun is_bi: Bool

Is self a well-formed BigInt (i.e. parsable via to_bi)

assert "123".is_bi
assert "-123".is_bi
assert not "0b1011".is_bi
assert not "123u8".is_bi
assert not "Not a BigInt".is_bi

fun is_r: Bool

Is self a well-formed Ratio (i.e. parsable via to_r)

assert "123".is_r
assert "-123".is_r
assert "1/2".is_r
assert "-1/2".is_r
assert not "-1/-2".is_r
assert not "0b1011".is_r
assert not "123u8".is_r
assert not "Not an Ratio".is_r

fun to_r: Ratio

If self contains a Ratio, return the corresponding Ratio

assert("123".to_r == 123.to_r)
assert("-123".to_r == -123.to_r)
assert("1/2".to_r == 0.5.to_r)
assert("-1/2".to_r == -0.5.to_r)

in sqlite3::sqlite3

in privileges::privileges

in cocoa::foundation

in java::ffi_support

in crapto::english_utils

in serialization::engine_tools

in sexp::sexp

in dom::parser

in json::serialization_write

redef fun accept_json_serializer(v)

Refinable service to customize the serialization of this class to JSON

This method can be refined to customize the serialization by either writing pure JSON directly on the stream v.stream or by using other services of JsonSerializer.

Most of the time, it is preferable to refine the method core_serialize_to which is used by all the serialization engines, not just JSON.

in json::static

fun parse_json: nullable Serializable

Parse self as JSON.

If self is not a valid JSON document or contains an unsupported escape sequence, return a JSONParseError.

Example with JsonObject:

var obj = "\{\"foo\": \{\"bar\": true, \"goo\": [1, 2, 3]\}\}".parse_json
assert obj isa JsonObject
assert obj["foo"] isa JsonObject
assert obj["foo"].as(JsonObject)["bar"] == true

Example with JsonArray:

var arr = "[1, 2, 3]".parse_json
assert arr isa JsonArray
assert arr.length == 3
assert arr.first == 1
assert arr.last == 3

Example with String:

var str = "\"foo, bar, baz\"".parse_json
assert str isa String
assert str == "foo, bar, baz"

Example of a syntax error:

var error = "\{foo: \"bar\"\}".parse_json
assert error isa JsonParseError
assert error.to_s == "Bad key format Error: bad JSON entity"

in json::dynamic

in json::serialization_read

in app::ui

in ios::ui::ui

in linux::ui

in mpi::mpi

in msgpack::serialization_write

redef fun accept_msgpack_serializer(v)

Hook to customize the serialization of this class to MessagePack

This method can be refined to customize the serialization by either writing pure JSON directly on the stream v.stream or by using other services of MsgPackSerializer.

Most of the time, it is better to refine the method core_serialize_to which is used by all the serialization engines, not just MessagePack.

in gamnit::bmfont

fun parse_bmfont(dir: String): MaybeError[BMFont, Error]

Parse self as an XML BMFont description file

Reports only basic XML format errors, other errors may be ignored or cause a crash.

var desc = """
<font>
  <info face="arial" size="72" bold="0" italic="0" charset=""
        unicode="1" stretchH="100" smooth="1" aa="1" padding="2,2,2,2"
        spacing="0,0" outline="0"/>
  <common lineHeight="80" base="65" scaleW="4030" scaleH="231"
          pages="1" packed="0"/>
  <pages>
    <page id="0" file="arial.png"/>
  </pages>
  <chars count="3">
    <char id="65" x="2519" y="10" width="55" height="59" xoffset="0"
          yoffset="13" xadvance="48" page="0" chnl="15"/>
    <char id="66" x="2600" y="10" width="46" height="58" xoffset="5"
          yoffset="13" xadvance="48" page="0" chnl="15"/>
    <char id="67" x="2673" y="9" width="52" height="60" xoffset="4"
          yoffset="12" xadvance="52" page="0" chnl="15"/>
  </chars>
  <kernings count="1">
    <kerning first="65" second="67" amount="-1"/>
  </kernings>
</font>
"""

var fnt = desc.parse_bmfont("dir_in_assets").value
assert fnt.to_s == "<BMFont arial at 72.0 pt, 1 pages, 3 chars>"
assert fnt.line_height == 80.0
assert fnt.kernings['A', 'C'] == -1.0
assert fnt.chars['A'].page.as(TextureAsset).path == "dir_in_assets/arial.png"

in android::ui::ui