# Enumerations

One way to use type aliases is to express an enumeration. For example, imagine we want to say something must either be Red, Blue or Green. We could write something like this:

```pony
primitive Red
primitive Blue
primitive Green

type Colour is (Red | Blue | Green)
```

There are two new concepts in there. The first is the type alias, introduced with the keyword `type`. It just means that the name that comes after `type` will be translated by the compiler to the type that comes after `is`.

The second new concept is the type that comes after `is`. It's not a single type! Instead, it's a __union__ type. You can read the `|` symbol as __or__ in this context, so the type is "Red or Blue or Green".

A union type is a form of _closed world_ type. That is, it says every type that can possibly be a member of it. In contrast, object-oriented subtyping is usually _open world_, e.g. in Java, an interface can be implemented by any number of classes.

You can also declare constants like in C or Go like this, making use of `apply`,
which can be omitted during call (will be discussed further in [Sugar](/expressions/sugar.md)),


@"llvm.usub.with.overflow.i128"(this, y)
else
let overflow = this < y
(this - y, overflow)
end

fun mulc(y: U128): (U128, Bool) =>
ifdef native128 then
@"llvm.umul.with.overflow.i128"(this, y)
else
let result = this * y
let overflow = (this != 0) and ((result / this) != y)
(result, overflow)
end

fun divc(y: U128): (U128, Bool) =>
_UnsignedCheckedArithmetic.div_checked[U128](this, y)

fun remc(y: U128): (U128, Bool) =>
_UnsignedCheckedArithmetic.rem_checked[U128](this, y)


"""
Private helper for `exists`, recursively working with `ListNode`s.
"""
try
if f(ln()?) then
true
else
_exists(ln.next() as this->ListNode[A], f)
end
else
false
end

fun partition(
f: {(this->A!): Bool} box)
: (List[this->A!]^, List[this->A!]^)
=>
"""
Builds a pair of `List`s, the first of which is made up of the elements
satisfying the predicate and the second of which is made up of


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


i: USize val)
: val->A ?

Parameters¶

i: USize val

Returns¶

val->A ?

update¶
[Source]
Return a vector with the i-th element changed, raising an error if the
index is out of bounds.
fun val update(
i: USize val,
value: val->A)
: Vec[A] val ?


This accepts a string iterator and returns a nested map of strings. If
parsing fails, an error is raised.
"""
let map = IniMap

let f = object
let map: IniMap = map

fun ref apply(section: String, key: String, value: String): Bool =>
try
if not map.contains(section) then
map.insert(section, Map[String, String])
end
map(section)?(key) = value
end
true

fun ref add_section(section: String): Bool =>
if not map.contains(section) then
map.insert(section, Map[String, String])


Promises[String val].join([p1; p2; p3].values())
.next[None]({(a: Array[String val] val) =>
for s in a.values() do
env.out.print(s)
end
})

p2("second")
p3("third")
p1("first")

fun box join(
ps: Iterator[Promise[A] tag] ref)
: Promise[Array[A] val] tag

Parameters¶

ps: Iterator[Promise[A] tag] ref

Returns¶


And we want to use this promise based API to look up the title of an issue.
Without `flatten_next`, we could attempt to do the following using `next`:

```pony
actor Main
new create(env: Env) =>
let repo: Promise[Repository] =
GitHub("my token").get_repo("ponylang/ponyc")

//
// do something with the repo once the promise is fulfilled
// in our case, get the issue
//

let issue = Promise[Promise[Issue]] =
repo.next[Promise[Issue]](FetchIssue~apply(1))

// once we get the issue, print the title
issue.next[None](PrintIssueTitle~apply(env.out))


the List in which it resides.

As you would expect functions are provided to create a ListNode, update a
ListNode's contained item, and pop the item from the ListNode.

Additional functions are provided to operate on a ListNode as part of a Linked
List. These provide for prepending, appending, removal, and safe traversal in
both directions.  The Ponylang
[collections.List](https://stdlib.ponylang.io/collections-List/) class is the
correct way to create these. _Do not attempt to create a Linked List using only
ListNodes._


VecValues[A: Any #share]¶
[Source]
class ref VecValues[A: Any #share]

Constructors¶
create¶
[Source]
new ref create(
v: Vec[A] val)
: VecValues[A] ref^

Parameters¶


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


Option val

arg¶
[Source]
Returns the Arg by name, defaulting to a fake Arg if unknown.
fun box arg(
name: String val)
: Arg val

Parameters¶

name: String val

Returns¶

Arg val


fun box add(
y: I32 val)
: I32 val

Parameters¶

y: I32 val

Returns¶

I32 val

sub¶
[Source]
fun box sub(
y: I32 val)
: I32 val

Parameters¶


Returns¶

None val

out¶
[Source]
If platform is debug configured, print message to standard output
fun box out(
msg: Stringable box = "")
: None val

Parameters¶

msg: Stringable box = ""

Returns¶

None val


fun ref _queue_read() =>
"""
Begin an IOCP read on Windows.
"""
ifdef windows then
try
@pony_os_recv(
_event,
_read_buf.cpointer(_read_buf_offset),
_read_buf.size() - _read_buf_offset) ?
else
hard_close()
end
end

fun ref _pending_reads() =>
"""
Unless this connection is currently muted, read while data is available,
guessing the next packet length as we go. If we read 5 kb of data, send


fun box tcpopt_sack_permit_hdr()
: I32 val

Returns¶

I32 val

tcpopt_signature¶
[Source]
fun box tcpopt_signature()
: I32 val

Returns¶

I32 val

tcpopt_timestamp¶
[Source]


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


fun micros(): U64 =>
"""
Monotonic unadjusted microseconds.
"""
ifdef osx then
@clock_gettime_nsec_np(_ClockUptimeRaw()) / 1000
elseif linux or bsd then
var ts = _clock_gettime(_ClockMonotonic)
((ts._1 * 1000000) + (ts._2 / 1000)).u64()
elseif windows then
_subseconds_from_query_performance_counter(1000000)
else
compile_error "unsupported platform"
end

fun nanos(): U64 =>
"""
Monotonic unadjusted nanoseconds.
"""
ifdef osx then


arg4: T4,
h: PropertyHelper val)
: None val ?

Parameters¶

arg1: T1
arg2: T2
arg3: T3
arg4: T4
h: PropertyHelper val

Returns¶

None val ?

name¶
[Source]
fun box name()


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


A

tanh¶
[Source]
fun box tanh()
: A

Returns¶

A

acos¶
[Source]
fun box acos()
: A

Returns¶


Public Functions¶
apply¶
[Source]
fun box apply()
: String val

Returns¶

String val

eq¶
[Source]
fun box eq(
that: ASCIIPunctuation val)
: Bool val

Parameters¶


Parameters¶

data: Array[U8 val] iso

prompt¶
[Source]
Pass a prompt along to the notifier.
be prompt(
value: String val)

Parameters¶

value: String val

size¶
[Source]
be size()


(U16 val , Bool val)

fld_partial¶
[Source]
fun box fld_partial(
y: U16 val)
: U16 val ?

Parameters¶

y: U16 val

Returns¶

U16 val ?

fld_unsafe¶
[Source]


// to inform the Pony runtime when to apply and release backpressure
// as the connection experiences it.
// Note the calls to
//
// Backpressure.apply(_auth)
// Backpressure.release(_auth)
//
// that apply and release backpressure as needed

use "backpressure"
use "collections"
use "net"

class SlowDown is TCPConnectionNotify
let _auth: ApplyReleaseBackpressureAuth
let _out: OutStream

new iso create(auth: ApplyReleaseBackpressureAuth, out: OutStream) =>
_auth = auth
_out = out


decode_url[optional A: Seq[U8 val] iso]¶
[Source]
Decode for URLs (RFC 4648).
fun box decode_url[optional A: Seq[U8 val] iso](
data: ReadSeq[U8 val] box)
: A^ ?

Parameters¶

data: ReadSeq[U8 val] box

Returns¶

A^ ?

decode[optional A: Seq[U8 val] iso]¶
[Source]
Configurable decoding. The defaults are for RFC 4648. Missing padding is


elseif (b.size() == b.space()) and (b.cpointer(b.size()) == cpointer())
then
(true, false)
else
(false, false)
end

if not unchoppable then
return (consume this, consume b)
end

if a_left then
_alloc = _alloc + b._alloc
_size = _size + b._size
consume this
else
b._alloc = b._alloc + _alloc
b._size = b._size + _size
consume b
end


if _size > 0 then
let chars = Array[U32](delim.size())

for rune in delim.runes() do
chars.push(rune)
end

var cur = recover String end
var i = USize(0)
var occur = USize(0)

try
while i < _size do
(let c, let len) = utf32(i.isize())?

if chars.contains(c) then
// If we find a delimiter, add the current string to the array.
occur = occur + 1

if (n > 0) and (occur >= n) then


Also, notice that `box` appears in the type. This is a __reference capability__. It means there is a certain class of operations we need to be able to do with a `K`. We'll cover this in more detail later.

Just like our other examples, all this really means is that `Map` is really a kind of `HashMap`.


y: I64 val

Returns¶

(I64 val , I64 val)

rem_unsafe¶
[Source]
fun box rem_unsafe(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶


"""
A function from A to B that is called when a promise is fulfilled.
"""
fun ref apply(value: A): B ?

interface iso Reject[A: Any #share]
"""
A function on A that is called when a promise is rejected.
"""
fun ref apply(): A ?

class iso FulfillIdentity[A: Any #share]
"""
An identity function for fulfilling promises.
"""
fun ref apply(value: A): A =>
consume value

class iso RejectAlways[A: Any #share]
"""


fun box ne(
that: Platform val)
: Bool val

Parameters¶

that: Platform val

Returns¶

Bool val


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


MapPairs[K: Any #share, V: Any #share, H: HashFunction[K] val]¶
[Source]
class ref MapPairs[K: Any #share, V: Any #share, H: HashFunction[K] val]

Constructors¶
create¶
[Source]
new ref create(
m: HashMap[K, V, H] val)
: MapPairs[K, V, H] ref^

Parameters¶


472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491


1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251


from: AmbientAuth val

Returns¶

StartProcessAuth val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: StartProcessAuth val)
: Bool val

Parameters¶

that: StartProcessAuth val

Returns¶


else
false
end

fun nodes(): ListNodes[A, this->ListNode[A]]^ =>
"""
Return an iterator on the nodes in the `List` in forward order.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let nodes = my_list.nodes()  // node with "a" is before node with "c"
```
"""
ListNodes[A, this->ListNode[A]](_head)

fun rnodes(): ListNodes[A, this->ListNode[A]]^ =>
"""
Return an iterator on the nodes in the `List` in reverse order.

```pony


[Source]
Create a readline handler to be passed to stdin. It begins blocked. Set an
initial prompt on the ANSITerm to begin processing.
new iso create(
notify: ReadlineNotify iso,
out: OutStream tag,
path: (FilePath val | None val) = reference,
maxlen: USize val = 0)
: Readline iso^

Parameters¶

notify: ReadlineNotify iso
out: OutStream tag
path: (FilePath val | None val) = reference
maxlen: USize val = 0

Returns¶

Readline iso^


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


key: String val,
value: String val)
: Bool val

Parameters¶

section: String val
key: String val
value: String val

Returns¶

Bool val

add_section¶
[Source]
This is called for every valid section in the INI file. Return false
to halt processing.
fun ref add_section(


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


"""
ip4(auth, "255.255.255.255", service)

fun broadcast_ip6(auth: DNSAuth, service: String)
: Array[NetAddress] iso^
=>
"""
Link-local IP6 broadcast address.
"""
ip6(auth, "FF02::1", service)

fun is_ip4(host: String): Bool =>
"""
Returns true if the host is a literal IPv4 address.
"""
@pony_os_host_ip4(host.cstring())

fun is_ip6(host: String): Bool =>
"""
Returns true if the host is a literal IPv6 address.


fun box netlink_no_enobufs()
: I32 val

Returns¶

I32 val

netlink_pktinfo¶
[Source]
fun box netlink_pktinfo()
: I32 val

Returns¶

I32 val

netlink_rdma¶
[Source]


fun box sctp_cwr_in_same_window()
: I32 val

Returns¶

I32 val

sctp_cwr_reduce_override¶
[Source]
fun box sctp_cwr_reduce_override()
: I32 val

Returns¶

I32 val

sctp_data¶
[Source]


Returns¶

Flags[A, B] iso^

sub¶
[Source]
This with the flag unset.
fun box sub(
flag: A)
: Flags[A, B] iso^

Parameters¶

flag: A

Returns¶

Flags[A, B] iso^


truncate¶
[Source]
Truncate the sequence to the given length, discarding excess elements.
If the sequence is already smaller than len, do nothing.
fun ref truncate(
len: USize val)
: None val

Parameters¶

len: USize val

Returns¶

None val

values¶
[Source]
Returns an iterator over the elements of the sequence.


PonyCheck is a library for property based testing
with tight integration into PonyTest.


fun box div_unsafe(
y: U64 val)
: U64 val

Parameters¶

y: U64 val

Returns¶

U64 val

divrem_unsafe¶
[Source]
fun box divrem_unsafe(
y: U64 val)
: (U64 val , U64 val)

Parameters¶


I128 val

shr_unsafe¶
[Source]
fun box shr_unsafe(
y: U128 val)
: I128 val

Parameters¶

y: U128 val

Returns¶

I128 val

add_unsafe¶
[Source]


fun ctz_unsafe(): U64 =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
@"llvm.cttz.i64"(this.u64(), true)

fun bitwidth(): U64 => 64

fun bytewidth(): USize => bitwidth().usize() / 8

fun min(y: I64): I64 => if this < y then this else y end
fun max(y: I64): I64 => if this > y then this else y end

fun fld(y: I64): I64 =>
_SignedArithmetic.fld[I64, U64](this, y)

fun fld_unsafe(y: I64): I64 =>
_SignedUnsafeArithmetic.fld_unsafe[I64, U64](this, y)


: Array[U8 val] iso^

Parameters¶

len: USize val

Returns¶

Array[U8 val] iso^

read_string¶
[Source]
Returns up to len bytes. The resulting string may have internal null
characters.
fun ref read_string(
len: USize val)
: String iso^

Parameters¶


u32¶
[Source]
Get the OS specific integer for a file mode. On Windows, if any read flag
is set, the path is made readable, and if any write flag is set, the path
is made writeable.
fun box u32()
: U32 val

Returns¶

U32 val


_stdin pipe.
be done_writing()

dispose¶
[Source]
Terminate child and close down everything.
be dispose()

timer_notify¶
[Source]
Windows IO polling timer has fired
be timer_notify()

Public Functions¶
expect¶
[Source]
A stdout call on the notifier must contain exactly qty bytes. If


primitive _STDINFILENO
fun apply(): U32 => 0

primitive _STDOUTFILENO
fun apply(): U32 => 1

primitive _STDERRFILENO
fun apply(): U32 => 2

// Operation not permitted
primitive _EPERM
fun apply(): I32 => 1

// No such process
primitive _ESRCH
fun apply(): I32 => 3

// Interrupted function
primitive _EINTR
fun apply(): I32 => 4


412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431


1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431


# Methods

All Pony code that actually does something, rather than defining types etc, appears in named blocks which are referred to as methods. There are three kinds of methods: functions, constructors, and behaviours. All methods are attached to type definitions (e.g. classes) - there are no global functions.

Behaviours are used for handling asynchronous messages sent to actors, which we've seen in the "Types" chapter [when we talked about actors](/types/actors.md#behaviours).

__Can I have some code outside of any methods like I do in Python?__ No. All Pony code must be within a method.


: Generator[U] box

Parameters¶

fn: {(T): U^}[T, U] box

Returns¶

Generator[U] box

flat_map[U: U]¶
[Source]
For each value of this generator, create a generator that is then combined.
fun box flat_map[U: U](
fn: {(T): Generator[U]}[T, U] box)
: Generator[U] box

Parameters¶


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831


embed _records: Array[_TestRecord] = Array[_TestRecord]
let _env: Env
let _timers: Timers = Timers
var _do_nothing: Bool = false
var _verbose: Bool = false
var _sequential: Bool = false
var _no_prog: Bool = false
var _list_only: Bool = false
var _started: USize = 0
var _finished: USize = 0
var _any_found: Bool = false
var _all_started: Bool = false

// Filtering options
var _exclude: String = ""
var _label: String = ""
var _only: String = ""

new create(env: Env, list: TestList tag) =>
"""


Returns¶

String val

i64¶
[Source]
Returns the option value as an I64, defaulting to 0.
fun box i64()
: I64 val

Returns¶

I64 val

u64¶
[Source]
Returns the option value as an U64, defaulting to 0.
fun box u64()


fun ref getsockopt(level: I32, option_name: I32, option_max_size: USize = 4): (U32, Array[U8] iso^) =>
"""
General wrapper for UDP sockets to the `getsockopt(2)` system call.

The caller must provide an array that is pre-allocated to be
at least as large as the largest data structure that the kernel
may return for the requested option.

In case of system call success, this function returns the 2-tuple:
1. The integer `0`.
2. An `Array[U8]` of data returned by the system call's `void *`
4th argument.  Its size is specified by the kernel via the
system call's `sockopt_len_t *` 5th argument.

In case of system call failure, this function returns the 2-tuple:
1. The value of `errno`.
2. An undefined value that must be ignored.

Usage example:


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


interface IniNotify
primitive IniParse


Public Functions¶
eq¶
[Source]
fun box eq(
that: EraseLine val)
: Bool val

Parameters¶

that: EraseLine val

Returns¶

Bool val

ne¶
[Source]


fun box u32_unsafe()
: U32 val

Returns¶

U32 val

u64_unsafe¶
[Source]
fun box u64_unsafe()
: U64 val

Returns¶

U64 val

u128_unsafe¶
[Source]


Parameters¶

offset: USize val

Returns¶

U8 val ?

read_u16[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Reads a U16 from offset. This is only allowed for an array of U8s.
fun box read_u16[optional B: (A & Real[B] val & U8 val)](
offset: USize val)
: U16 val ?

Parameters¶

offset: USize val


fun spec() : CommandSpec box =>
"""
Returns the spec for this command.
"""
_spec

fun fullname() : String =>
"""
Returns the full name of this command, with its parents prefixed.
"""
_fullname

fun option(name: String): Option =>
"""
Returns the Option by name, defaulting to a fake Option if unknown.
"""
try _options(name)? else Option(OptionSpec.bool(name), false) end

fun arg(name: String): Arg =>
"""


_SignedCheckedArithmetic.div_checked[I8, U8](this, y)

fun remc(y: I8): (I8, Bool) =>
_SignedCheckedArithmetic.rem_checked[I8, U8](this, y)

fun fldc(y: I8): (I8, Bool) =>
_SignedCheckedArithmetic.fld_checked[I8, U8](this, y)

fun modc(y: I8): (I8, Bool) =>
_SignedCheckedArithmetic.mod_checked[I8, U8](this, y)

fun add_partial(y: I8): I8 ? =>
_SignedPartialArithmetic.add_partial[I8](this, y)?

fun sub_partial(y: I8): I8 ? =>
_SignedPartialArithmetic.sub_partial[I8](this, y)?

fun mul_partial(y: I8): I8 ? =>
_SignedPartialArithmetic.mul_partial[I8](this, y)?


fun find(
value: A!,
offset: USize = 0,
nth: USize = 0,
predicate: {(box->A!, box->A!): Bool} val = {(l, r) => l is r })
: USize ?
=>
"""
Find the `nth` appearance of `value` from the beginning of the array,
starting at `offset` and examining higher indices, and using the supplied
`predicate` for comparisons. Returns the index of the value, or raise an
error if the value isn't present.

By default, the search starts at the first element of the array, returns
the first instance of `value` found, and uses object identity for
comparison.
"""
var i = offset
var n = USize(0)


A

eq¶
[Source]
fun box eq(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶

Bool val

ne¶


FileErrNo¶
[Source]
type FileErrNo is
(FileOK val | FileError val | FileEOF val | FileBadFileNumber val | FileExists val | FilePermissionDenied val)

Type Alias For¶

(FileOK val | FileError val | FileEOF val | FileBadFileNumber val | FileExists val | FilePermissionDenied val)


Bool val

exists¶
[Source]
Returns true if at least one element satisfies the provided predicate,
false otherwise.
fun val exists(
f: {(val->A): Bool}[A] box)
: Bool val

Parameters¶

f: {(val->A): Bool}[A] box

Returns¶

Bool val


72
73
74"""


fld_unsafe¶
[Source]
Unsafe operation.
If any input or output of the operation is +/- infinity or NaN, the result
is undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
fun box fld_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A

divrem_unsafe¶


fun ref u16_be(data: U16) =>
"""
Write a U16 to the buffer in big-endian byte order.
"""
let num_bytes = U16(0).bytewidth()
ifdef bigendian then
_current.push_u16(data)
else
_current.push_u16(data.bswap())
end
_size = _size + num_bytes

fun ref i16_le(data: I16) =>
"""
Write an I16 to the buffer in little-endian byte order.
"""
u16_le(data.u16())

fun ref i16_be(data: I16) =>


fun box so_peek_off()
: I32 val

Returns¶

I32 val

so_peercred¶
[Source]
fun box so_peercred()
: I32 val

Returns¶

I32 val

so_peerlabel¶
[Source]


Bool val

ne¶
[Source]
fun box ne(
that: FormatBinary val)
: Bool val

Parameters¶

that: FormatBinary val

Returns¶

Bool val


A

add¶
[Source]
fun box add(
y: A)
: A

Parameters¶

y: A

Returns¶

A

sub¶


## Multibyte Character literals

It is possible to have character literals that contain multiple characters. The resulting integer value is constructed byte by byte with each character representing a single byte in the resulting integer, the last character being the least significant byte:

```pony
let multiByte: U64 = 'ABCD' // 0x41424344
```


312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


Peek at a big-endian U16.
fun box peek_u16_be(
offset: USize val = 0)
: U16 val ?

Parameters¶

offset: USize val = 0

Returns¶

U16 val ?

peek_u16_le¶
[Source]
Peek at a little-endian U16.
fun box peek_u16_le(
offset: USize val = 0)
: U16 val ?


Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: EnvVars val)
: Bool val

Parameters¶

that: EnvVars val

Returns¶

Bool val


y: I128 val

Returns¶

I128 val

sub¶
[Source]
fun box sub(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶


fun box tcp_md5sig_maxkeylen()
: I32 val

Returns¶

I32 val

tcp_minmss¶
[Source]
fun box tcp_minmss()
: I32 val

Returns¶

I32 val

tcp_mss¶
[Source]


172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191


match _ValueParser.parse(spec._typ_p(), a)
| let v: _Value => Option(spec, v)
| let se: SyntaxError => se
end
else
if not spec._requires_arg() then
Option(spec, spec._default_arg())
else
SyntaxError(spec.name(), "missing arg for option")
end
end

primitive _ArgParser
fun parse(spec: ArgSpec, arg: String): (Arg | SyntaxError) =>
match _ValueParser.parse(spec._typ_p(), arg)
| let v: _Value => Arg(spec, v)
| let se: SyntaxError => se
end

primitive _ValueParser


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


U64 val | U128 val | ULong val |
USize val) & Integer[B] val)] is
Comparable[Flags[A, B] box] ref

Implements¶

Comparable[Flags[A, B] box] ref

Constructors¶
create¶
[Source]
Create a Flags instance with an optional initial value.
Default is 0 (no flags set).
new iso create(
value': B = 0)
: Flags[A, B] iso^

Parameters¶


net_address.pony

1
2
3
4
5
6
7
8
9
10
11


i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶

I8 val

i16_unsafe¶
[Source]
fun box i16_unsafe()
: I16 val

Returns¶

I16 val


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


_name = name'
_descr = descr'
(_typ, _default, _required) = _init(_BoolType, default')

new val string(
name': String,
descr': String = "",
default': (String | None) = None)
=>
"""
Creates an Arg with a String typed value that can be used like
`<cmd> filename`
to yield an arg value
`cmd.arg("file").string() == "filename"`.
"""
_name = name'
_descr = descr'
(_typ, _default, _required) = _init(_StringType, default')

new val i64(name': String,


fun box icmp_host_isolated()
: I32 val

Returns¶

I32 val

icmp_host_unknown¶
[Source]
fun box icmp_host_unknown()
: I32 val

Returns¶

I32 val

icmp_host_unreach¶
[Source]


332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351


592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611


None val

writev¶
[Source]
Write ByteSeqs to the buffer.
fun ref writev(
data: ByteSeqIter val)
: None val

Parameters¶

data: ByteSeqIter val

Returns¶

None val


# Linking to C Libraries

If Pony code calls FFI functions, then those functions, or rather the libraries containing them, must be linked into the Pony program.


Bool val


Return an iterator that alternates the values of the original iterator and
the other until one of them runs out.


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


"""
Complete an expected action successfully.

If all expected actions are completed successfully,
the property is considered successful.

If 1 action fails, the property is considered failing.

If the action `name` was not expected, i.e. was not registered using
`expect_action`, nothing happens.
"""
_runner.complete_action(name, _run, this)

fun val fail_action(name: String) =>
"""
Mark an expected action as failed.

If all expected actions are completed successfully,
the property is considered successful.


y: ULong val

Returns¶

(ULong val , Bool val)

remc¶
[Source]
fun box remc(
y: ULong val)
: (ULong val , Bool val)

Parameters¶

y: ULong val

Returns¶


[Source]
fun ref u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun ref ulong()
: ULong val

Returns¶

ULong val

usize¶


: Generator[HashSet[T, HashIs[T!] val] ref] box

Parameters¶

gen: Generator[T] box
max: USize val = 100

Returns¶

Generator[HashSet[T, HashIs[T!] val] ref] box

map_of[K: (Hashable #read & Equatable[K] #read), V: V]¶
[Source]
Create a generator for Map from a generator of key-value tuples.
The generated maps will have a size up to max,
but tend to have fewer entries depending on the source generator gen.
If the generator generates key-value pairs with
duplicate keys (based on structural equality),
the pair that is generated later will overwrite earlier entries in the map.


fun box so_detach_filter()
: I32 val

Returns¶

I32 val

so_domain¶
[Source]
fun box so_domain()
: I32 val

Returns¶

I32 val

so_dontlinger¶
[Source]


fun box ipproto_icmpv6()
: I32 val

Returns¶

I32 val

ipproto_idp¶
[Source]
fun box ipproto_idp()
: I32 val

Returns¶

I32 val

ipproto_idpr¶
[Source]


## Tear Down

Each unit test object may define a [tear_down()](pony_test-UnitTest.md#tear_down) function. This is called after
the test has finished to allow tearing down of any complex environment that had
to be set up for the test.

The [tear_down()](pony_test-UnitTest.md#tear_down) function is called for each test regardless of whether it
passed or failed. If a test times out [tear_down()](pony_test-UnitTest.md#tear_down) will be called after
timed_out() returns.

When a test is in an exclusion group, the [tear_down()](pony_test-UnitTest.md#tear_down) call is considered part
of the tests run. The next test in the exclusion group will not start until
after [tear_down()](pony_test-UnitTest.md#tear_down) returns on the current test.

The test's [TestHelper](pony_test-TestHelper.md) is handed to [tear_down()](pony_test-UnitTest.md#tear_down) and it is permitted to log
messages and call assert functions during tear down.


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


gen: Generator[T] box
min: USize val = 0
max: USize val = 100

Returns¶

Generator[Array[T] ref] box

shuffled_array_gen[T: T]¶
[Source]
fun box shuffled_array_gen[T: T](
gen: Generator[Array[T] ref] box)
: Generator[Array[T] ref] box

Parameters¶

gen: Generator[Array[T] ref] box

Returns¶


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


_OSSocket.u32_to_bytes4(if state then 1 else 0 end)
_OSSocket.setsockopt(_fd, OSSockOpt.sol_socket(), OSSockOpt.so_broadcast(), word)

fun ref set_so_rcvbuf(bufsize: U32): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, SO_RCVBUF, ...)`
"""
_OSSocket.set_so_rcvbuf(_fd, bufsize)

fun ref set_so_sndbuf(bufsize: U32): U32 =>
"""
Wrapper for the FFI call `setsockopt(fd, SOL_SOCKET, SO_SNDBUF, ...)`
"""
_OSSocket.set_so_sndbuf(_fd, bufsize)


| let os: Array[Option] =>
for o in os.values() do
if o.spec()._typ_p().is_seq() then
options.upsert(o.spec().name(), o, {(x, n) => x._append(n) })
else
options.update(o.spec().name(), o)
end
end
| let se: SyntaxError =>
return se
end

else // no dashes, must be a command or an arg
if _spec.commands().size() > 0 then
try
match _spec.commands()(token)?
| let cs: CommandSpec box =>
return CommandParser._sub(cs, this).
_parse_command(tokens, options, args, envsmap, opt_stop)
end


ctrl: Bool val = false
alt: Bool val = false
shift: Bool val = false

Returns¶

None val

delete¶
[Source]
Forward delete.
fun ref delete(
ctrl: Bool val = false,
alt: Bool val = false,
shift: Bool val = false)
: None val

Parameters¶


fun ref property(arg1: (T1, T2, T3, T4), h: PropertyHelper) ? =>
(let x1, let x2, let x3, let x4) = consume arg1
property4(consume x1, consume x2, consume x3, consume x4, h)?

fun ref property4(arg1: T1, arg2: T2, arg3: T3, arg4: T4, h: PropertyHelper) ?
"""
A method verifying that a certain property holds for all given
`arg1`, `arg2`, `arg3`, and `arg4`
with the help of [PropertyHelper](pony_check-PropertyHelper.md) `h`.
"""


fun box ip_multicast_ifindex()
: I32 val

Returns¶

I32 val

ip_multicast_loop¶
[Source]
fun box ip_multicast_loop()
: I32 val

Returns¶

I32 val

ip_multicast_ttl¶
[Source]


fun box fchown()
: U64 val

Returns¶

U64 val

fchownat¶
[Source]
fun box fchownat()
: U64 val

Returns¶

U64 val

fcntl¶
[Source]


(A , Bool val)

remc¶
[Source]
fun box remc(
y: A)
: (A , Bool val)

Parameters¶

y: A

Returns¶

(A , Bool val)

fldc¶
[Source]


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


copysign¶
[Source]
fun box copysign(
sign: F64 val)
: F64 val

Parameters¶

sign: F64 val

Returns¶

F64 val

hash¶
[Source]
fun box hash()
: USize val


len: USize = -1)
=>
"""
Append the elements from a sequence, starting from the given offset.
"""
if offset >= seq.size() then
return
end

let copy_len = len.min(seq.size() - offset)
reserve(_size + copy_len)

var n = USize(0)

try
while n < copy_len do
_ptr._update(_size + n, seq(offset + n)?)

n = n + 1
end


fun msg_notification():I32 => @pony_os_sockopt_option(I32(382))
fun msg_socallbck():I32 => @pony_os_sockopt_option(I32(383))
fun ndrvproto_ndrv():I32 => @pony_os_sockopt_option(I32(384))
fun ndrv_addmulticast():I32 => @pony_os_sockopt_option(I32(385))
fun ndrv_deldmxspec():I32 => @pony_os_sockopt_option(I32(386))
fun ndrv_delmulticast():I32 => @pony_os_sockopt_option(I32(387))
fun ndrv_demuxtype_ethertype():I32 => @pony_os_sockopt_option(I32(388))
fun ndrv_demuxtype_sap():I32 => @pony_os_sockopt_option(I32(389))
fun ndrv_demuxtype_snap():I32 => @pony_os_sockopt_option(I32(390))
fun ndrv_dmux_max_descr():I32 => @pony_os_sockopt_option(I32(391))
fun ndrv_protocol_desc_vers():I32 => @pony_os_sockopt_option(I32(392))
fun ndrv_setdmxspec():I32 => @pony_os_sockopt_option(I32(393))
fun netlink_add_membership():I32 => @pony_os_sockopt_option(I32(394))
fun netlink_audit():I32 => @pony_os_sockopt_option(I32(395))
fun netlink_broadcast_error():I32 => @pony_os_sockopt_option(I32(396))
fun netlink_cap_ack():I32 => @pony_os_sockopt_option(I32(397))
fun netlink_connector():I32 => @pony_os_sockopt_option(I32(398))
fun netlink_crypto():I32 => @pony_os_sockopt_option(I32(399))
fun netlink_dnrtmsg():I32 => @pony_os_sockopt_option(I32(400))
fun netlink_drop_membership():I32 => @pony_os_sockopt_option(I32(401))


```pony
foo1(2, 3) = x
foo2() = x
foo3(37, "Hello", 3.5 where a = 2, b = 3) = x
```

__Does it matter where `value` appears in my parameter list?__ Whilst it doesn't strictly matter it is good practice to put `value` as the last parameter. That way all of the others can be specified by position.


A

divrem_unsafe¶
[Source]
fun box divrem_unsafe(
y: A)
: (A , A)

Parameters¶

y: A

Returns¶

(A , A)

rem_unsafe¶


fun box sctp_fragment_interleave()
: I32 val

Returns¶

I32 val

sctp_frag_level_0¶
[Source]
fun box sctp_frag_level_0()
: I32 val

Returns¶

I32 val

sctp_frag_level_1¶
[Source]


fun box u32_unsafe()
: U32 val

Returns¶

U32 val

u64_unsafe¶
[Source]
fun box u64_unsafe()
: U64 val

Returns¶

U64 val

u128_unsafe¶
[Source]


I128 val

ilong¶
[Source]
fun box ilong()
: ILong val

Returns¶

ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶


[Source]
fun box mod_unsafe(
y: A)
: A

Parameters¶

y: A

Returns¶

A

shl_unsafe¶
[Source]
Unsafe operation.
If non-zero bits are shifted-out, the result is undefined.
fun box shl_unsafe(
y: A)


interface Equatable[A: Equatable[A] #read]
fun eq(that: box->A): Bool => this is that
fun ne(that: box->A): Bool => not eq(that)

interface Comparable[A: Comparable[A] #read] is Equatable[A]
fun lt(that: box->A): Bool
fun le(that: box->A): Bool => lt(that) or eq(that)
fun ge(that: box->A): Bool => not lt(that)
fun gt(that: box->A): Bool => not le(that)

fun compare(that: box->A): Compare =>
if eq(that) then
Equal
elseif lt(that) then
Less
else
Greater
end


fun box sctp_pr_supported()
: I32 val

Returns¶

I32 val

sctp_reconfig_supported¶
[Source]
fun box sctp_reconfig_supported()
: I32 val

Returns¶

I32 val

sctp_recvnxtinfo¶
[Source]


# FFI and monopolizing the scheduler

An easy way to monopolize a scheduler thread is to use the FFI facilities of Pony to kick off code that doesn't return for an extended period of time. You do not want to do this. Do not call FFI code that doesn't return in a reasonable amount of time.


do_not_optimise.pony

1
2
3
4
5
6
7
8
9
10
11


newly established connection to the server.
"""


ring_buffer.pony

1
2
3
4
5
6
7
8
9
10
11


var _hunger_level: U64

new ref create(name': String, level: U64) =>
name = name'
set_hunger_level(level)
// Error: field _hunger_level left undefined in constructor

fun ref set_hunger_level(hunger_level: U64) =>
_hunger_level = hunger_level
```

We will see later in the Methods section that a class can have several constructors. For now, just remember that if the assignment of a field is not done at the definition level, it has to be done in each constructor of the class the field belongs to.

As for variables, using `var` means a field can be assigned and reassigned as many times as you like in the class. Using `let` means the field can only be assigned once.

```pony
class Wombat
let name: String
var _hunger_level: U64


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


this >>~ y

fun popcount(): B
fun clz(): B
fun ctz(): B

fun clz_unsafe(): B
"""
Unsafe operation.
If this is 0, the result is undefined.
"""

fun ctz_unsafe(): B
"""
Unsafe operation.
If this is 0, the result is undefined.
"""

fun bitwidth(): B


fun box sctp_cc_hstcp()
: I32 val

Returns¶

I32 val

sctp_cc_htcp¶
[Source]
fun box sctp_cc_htcp()
: I32 val

Returns¶

I32 val

sctp_cc_option¶
[Source]


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


delete(_size - 1)?

fun ref unshift(value: A) =>
"""
Add an element to the beginning of the array.
"""
try
insert(0, consume value)?
end

fun ref shift(): A^ ? =>
"""
Remove an element from the beginning of the array.
The removed element is returned.
"""
delete(0)?

fun ref append(
seq: (ReadSeq[A] & ReadElement[A^]),
offset: USize = 0,


fun box usize_unsafe()
: USize val

Returns¶

USize val

f32_unsafe¶
[Source]
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]


[Source]
fun box sub(
y: A)
: A

Parameters¶

y: A

Returns¶

A

mul¶
[Source]
fun box mul(
y: A)
: A


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

eq¶
[Source]
fun box eq(
that: FileRead val)
: Bool val

Parameters¶


## Unsafe Floating Point Arithmetic

Unsafe Floating Point operations do not necessarily comply with IEEE 754 for every input or every result. If any argument to an unsafe operation or its result are `+/-Inf` or `NaN`, the result is actually undefined.

This allows more aggressive optimizations and for faster execution, but only yields valid results for values different that the exceptional values `+/-Inf` and `NaN`. We suggest to only use unsafe arithmetic on floats if you can exclude those cases.

---

| Operator | Method       |
| -------- | ------------ |
| `+~`     | `add_unsafe()` |
| `-~`     | `sub_unsafe()` |
| `*~`     | `mul_unsafe()` |
| `/~`     | `div_unsafe()` |
| `%~`     | `rem_unsafe()` |
| `%%~`    | `mod_unsafe()` |
| `-~`     | `neg_unsafe()` |
| `<~`     | `lt_unsafe()`  |
| `>~`     | `gt_unsafe()`  |
| `<=~`    | `le_unsafe()`  |


F64 val

compare¶
[Source]
fun box compare(
that: box->A)
: (Less val | Equal val | Greater val)

Parameters¶

that: box->A

Returns¶

(Less val | Equal val | Greater val)


while true do
var left = (2 * idx) + 1
if (left >= n) or (left < 0) then
break
end
let right = left + 1
if (right < n) and P(_data(right)?, _data(left)?) then
left = right
end
if not P(_data(left)?, _data(idx)?) then
break
end
_data.swap_elements(idx, left)?
idx = left
end
end
idx > start

fun _apply(i: USize): this->A ? =>
_data(i)?


fun box op_or(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

op_xor¶
[Source]
fun box op_xor(
y: U32 val)
: U32 val

Parameters¶


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


: HashMap[this->K!, this->V!, H2] ref^

Parameters¶

key: this->K!
value: this->V!

Returns¶

HashMap[this->K!, this->V!, H2] ref^

sub[optional H2: HashFunction[this->K!] val]¶
[Source]
This without the given key.
fun box sub[optional H2: HashFunction[this->K!] val](
key: this->K!)
: HashMap[this->K!, this->V!, H2] ref^

Parameters¶


splitmix64.pony

1
2
3
4
5
6
7
8
9
10
11


Returns¶

U8 val ?

unshift¶
[Source]
Adds a byte to the beginning of the string.
fun ref unshift(
value: U8 val)
: None val

Parameters¶

value: U8 val

Returns¶

None val


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


fun box mod(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶

I64 val

mod_unsafe¶
[Source]
fun box mod_unsafe(
y: I64 val)
: I64 val

Parameters¶


1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


i: U64 val

Returns¶

F64 val^

from[B: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[B] val)]¶
[Source]
new val from[B: ((I8 val | I16 val | I32 val |
I64 val | I128 val | ILong val |
ISize val | U8 val | U16 val |
U32 val | U64 val | U128 val |
ULong val | USize val | F32 val |
F64 val) & Real[B] val)](
a: B)
: F64 val^

Parameters¶


Time¶
[Source]
A collection of ways to fetch the current time.
primitive val Time

Constructors¶
create¶
[Source]
new val create()
: Time val^

Returns¶


fun box sctp_pcb_flags_blocking_io()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_boundall¶
[Source]
fun box sctp_pcb_flags_boundall()
: I32 val

Returns¶

I32 val

sctp_pcb_flags_bound_v6¶
[Source]


[Source]
fun box write()
: U32 val

Returns¶

U32 val

timer¶
[Source]
fun box timer()
: U32 val

Returns¶

U32 val

signal¶


fun box so_group_id()
: I32 val

Returns¶

I32 val

so_group_priority¶
[Source]
fun box so_group_priority()
: I32 val

Returns¶

I32 val

so_hci_raw_direction¶
[Source]


U8 val

u16_unsafe¶
[Source]
fun box u16_unsafe()
: U16 val

Returns¶

U16 val

u32_unsafe¶
[Source]
fun box u32_unsafe()
: U32 val

Returns¶


Returns true if the array contains value, false otherwise.
The default predicate checks for matches by identity. To search for matches
by structural equality, pass an object literal such as {(l, r) => l == r}.
fun box contains(
value: A!,
predicate: {(box->A!, box->A!): Bool}[A] val = lambda)
: Bool val

Parameters¶

value: A!
predicate: {(box->A!, box->A!): Bool}[A] val = lambda

Returns¶

Bool val

rfind¶
[Source]


(U128 val , U128 val)

div_unsafe¶
[Source]
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
fun box div_unsafe(
y: U128 val)
: U128 val

Parameters¶

y: U128 val

Returns¶

U128 val


fun box dccp_sockopt_change_r()
: I32 val

Returns¶

I32 val

dccp_sockopt_get_cur_mps¶
[Source]
fun box dccp_sockopt_get_cur_mps()
: I32 val

Returns¶

I32 val

dccp_sockopt_packet_size¶
[Source]


ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
[Source]
fun box u8()
: U8 val

Returns¶


end

fun rename(source: String, to: Directory box, target: String): Bool =>
"""
Rename source (which is relative to this directory) to target (which is
relative to the `to` directory).
"""
if
not path.caps(FileLookup)
or not path.caps(FileRename)
or not to.path.caps(FileLookup)
or not to.path.caps(FileCreate)
or (_fd == -1)
or (to._fd == -1)
then
return false
end

try
let path' = FilePath.from(path, source, path.caps)?


# Enumeration which can be iterated

```pony
primitive Black
primitive Blue
primitive Red
primitive Yellow

type Colour is (Black | Blue | Red | Yellow)

primitive ColourList
fun tag apply(): Array[Colour] =>
[Black; Blue; Red; Yellow]

for colour in ColourList().values() do
end
```


fun box accept()
: U64 val

Returns¶

U64 val

bind¶
[Source]
fun box bind()
: U64 val

Returns¶

U64 val

connect¶
[Source]


fun ref u8(data: U8) =>
"""
Write a byte to the buffer.
"""
let num_bytes = U8(0).bytewidth()
_current.push_u8(data)
_size = _size + num_bytes

fun ref u16_le(data: U16) =>
"""
Write a U16 to the buffer in little-endian byte order.
"""
let num_bytes = U16(0).bytewidth()
ifdef littleendian then
_current.push_u16(data)
else
_current.push_u16(data.bswap())
end
_size = _size + num_bytes


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


ULong val

sub¶
[Source]
fun box sub(
y: ULong val)
: ULong val

Parameters¶

y: ULong val

Returns¶

ULong val

mul¶
[Source]


fun box tipc_conn_shutdown()
: I32 val

Returns¶

I32 val

tipc_conn_timeout¶
[Source]
fun box tipc_conn_timeout()
: I32 val

Returns¶

I32 val

tipc_critical_importance¶
[Source]


An extended key.
"""
match _esc_num
| 1 => _home()
| 2 => _insert()
| 3 => _delete()
| 4 => _end()
| 5 => _page_up()
| 6 => _page_down()
| 11 => _fn_key(1)
| 12 => _fn_key(2)
| 13 => _fn_key(3)
| 14 => _fn_key(4)
| 15 => _fn_key(5)
| 17 => _fn_key(6)
| 18 => _fn_key(7)
| 19 => _fn_key(8)
| 20 => _fn_key(9)
| 21 => _fn_key(10)
| 23 => _fn_key(11)


TestList¶
[Source]
Source of unit tests for a PonyTest object.
See package doc string for further information and example use.
trait ref TestList

Public Functions¶
tests¶
[Source]
Add all the tests in this suite to the given test object.
Typically the implementation of this function will be of the form:
fun tests(test: PonyTest) =>
test(_TestClass1)


fun box rose_holdback()
: I32 val

Returns¶

I32 val

rose_idle¶
[Source]
fun box rose_idle()
: I32 val

Returns¶

I32 val

rose_invalid_facility¶
[Source]


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


fun box sctp_adaptation_layer()
: I32 val

Returns¶

I32 val

sctp_adaption_layer¶
[Source]
fun box sctp_adaption_layer()
: I32 val

Returns¶

I32 val

sctp_add_streams¶
[Source]


"""
Unchops two iso strings to return the original string they were chopped
from. Both input strings are isolated and mutable and were originally
chopped from a single string. This function checks that they are indeed two
strings chopped from the same original string and can be unchopped before
doing the unchopping and returning the unchopped string. If the two strings
cannot be unchopped it returns both strings without modifying them.
The operation does not allocate a new string pointer nor copy elements.
"""
if _size == 0 then
return consume b
end

if b.size() == 0 then
return consume this
end

(let unchoppable, let a_left) =
if (_size == _alloc) and (cpointer(_size) == b.cpointer()) then
(true, true)


y: F32 val

Returns¶

F32 val

div¶
fun box div(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val


fun box sctp_enable_stream_reset()
: I32 val

Returns¶

I32 val

sctp_enable_value_mask¶
[Source]
fun box sctp_enable_value_mask()
: I32 val

Returns¶

I32 val

sctp_established¶
[Source]


When any assertion function fails the test is counted as a fail. However, tests
can also indicate failure by raising an error in the test function.


72
73
74
75
76
77
78primitive Sort[A: Seq[B] ref, B: Comparable[B] #read]
"""
Implementation of dual-pivot quicksort.  It operates in-place on the provided Seq, using
a small amount of additional memory. The nature of the element-realation is expressed via
the supplied comparator.

(The following is paraphrased from [Wikipedia](https://en.wikipedia.org/wiki/Quicksort).)

Quicksort is a common implementation of a sort algorithm which can sort items of any type
for which a "less-than" relation (formally, a total order) is defined.

On average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case,
it makes O(n2) comparisons, though this behavior is rare.  Multi-pivot implementations
(of which dual-pivot is one) make efficient use of modern processor caches.


new tag ip6(
auth: TCPConnectAuth val,
notify: TCPConnectionNotify iso,
host: String val,
service: String val,
from: String val = "",
read_buffer_size: USize val = 16384,
yield_after_reading: USize val = 16384,
yield_after_writing: USize val = 16384)
: TCPConnection tag^

Parameters¶

auth: TCPConnectAuth val
notify: TCPConnectionNotify iso
host: String val
service: String val
from: String val = ""
read_buffer_size: USize val = 16384
yield_after_reading: USize val = 16384


Sort[A: Seq[B] ref, B: Comparable[B] #read]¶
[Source]
Implementation of dual-pivot quicksort.  It operates in-place on the provided Seq, using
a small amount of additional memory. The nature of the element-realation is expressed via
the supplied comparator.
(The following is paraphrased from Wikipedia.)
Quicksort is a common implementation of a sort algorithm which can sort items of any type
for which a "less-than" relation (formally, a total order) is defined.
On average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case,
it makes O(n2) comparisons, though this behavior is rare.  Multi-pivot implementations
(of which dual-pivot is one) make efficient use of modern processor caches.
Example program¶
The following takes an reverse-alphabetical array of Strings ("third", "second", "first"),


fun f32_unsafe(): F32 =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
f64_unsafe().f32_unsafe()

fun f64_unsafe(): F64 =>
"""
Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
f64()

fun addc(y: I128): (I128, Bool) =>
ifdef native128 then
@"llvm.sadd.with.overflow.i128"(this, y)
else
let overflow =


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


Lists[A: A]¶
[Source]
A primitive containing helper functions for constructing and
testing Lists.
primitive val Lists[A: A]

Constructors¶
create¶
[Source]
new val create()
: Lists[A] val^

Returns¶


end

fun ctz(): ULong =>
ifdef ilp32 or llp64 then
@"llvm.cttz.i32"(this.u32(), false).ulong()
else
@"llvm.cttz.i64"(this.u64(), false).ulong()
end

fun clz_unsafe(): ULong =>
ifdef ilp32 or llp64 then
@"llvm.ctlz.i32"(this.u32(), true).ulong()
else
@"llvm.ctlz.i64"(this.u64(), true).ulong()
end

fun ctz_unsafe(): ULong =>
ifdef ilp32 or llp64 then
@"llvm.cttz.i32"(this.u32(), false).ulong()
else


U128 val

ulong_unsafe¶
[Source]
fun box ulong_unsafe()
: ULong val

Returns¶

ULong val

usize_unsafe¶
[Source]
fun box usize_unsafe()
: USize val

Returns¶


Bool val


fun box ilong()
: ILong val

Returns¶

ILong val

isize¶
[Source]
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
[Source]


Returns¶

F32 val ?

peek_f64_be¶
[Source]
Peek at a big-endian F64.
fun box peek_f64_be(
offset: USize val = 0)
: F64 val ?

Parameters¶

offset: USize val = 0

Returns¶

F64 val ?


let params = prop.params()
h.long_test(params.timeout)
let property_runner =
PropertyRunner[T](
consume prop,
params,
h, // treat it as PropertyResultNotify
h,  // is also a PropertyLogger for us
h.env
)
h.dispose_when_done(property_runner)
property_runner.run()

class iso Property2UnitTest[T1, T2] is UnitTest

var _prop2: ( Property2[T1, T2] iso | None )
let _name: String

new iso create(p2: Property2[T1, T2] iso, name': (String | None) = None) =>
_name =


192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211


new val _create(path': String, caps': FileCaps val) =>
"""
Internal constructor.
"""
path = path'
caps.union(caps')

fun val join(
path': String,
caps': FileCaps val = recover val FileCaps .> all() end)
: FilePath ?
=>
"""
Return a new path relative to this one.
"""
from(this, path', caps')?

fun val walk(handler: WalkHandler ref, follow_links: Bool = false) =>
"""


passed or failed. If a test times out tear_down() will be called after
timed_out() returns.
When a test is in an exclusion group, the tear_down() call is considered part
of the tests run. The next test in the exclusion group will not start until
after tear_down() returns on the current test.
The test's TestHelper is handed to tear_down() and it is permitted to log
messages and call assert functions during tear down.
Example¶
The following example creates a temporary directory in the set_up() function
and removes it in the tear_down() function, thus
simplifying the test function itself:
use "pony_test"
use "files"

class iso TempDirTest
var tmp_dir: (FilePath | None) = None

fun name(): String => "temp-dir"

fun ref set_up(h: TestHelper)? =>


U8¶
[Source]
primitive val U8 is
UnsignedInteger[U8 val] val

Implements¶

UnsignedInteger[U8 val] val

Constructors¶
create¶
[Source]


732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751


932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951


Calculates the remainder of this number divided by `y`.

Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""
this %~ y

fun fld_unsafe(y: A): A
"""
Floored division, rounded towards negative infinity,
as opposed to `div` which rounds towards zero.

*Unsafe Operation*

If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""

fun mod_unsafe(y: A): A


[Source]

Public Functions¶
string¶
[Source]
fun box string()
: String iso^

Returns¶

String iso^


fun box op_or(
y: I16 val)
: I16 val

Parameters¶

y: I16 val

Returns¶

I16 val

op_xor¶
[Source]
fun box op_xor(
y: I16 val)
: I16 val

Parameters¶


I32 val

fld_unsafe¶
[Source]
fun box fld_unsafe(
y: I32 val)
: I32 val

Parameters¶

y: I32 val

Returns¶

I32 val

mod¶
[Source]


fun box u8()
: U8 val

Returns¶

U8 val

u16¶
[Source]
fun box u16()
: U16 val

Returns¶

U16 val

u32¶
[Source]


F64 val

i8_unsafe¶
[Source]
fun box i8_unsafe()
: I8 val

Returns¶

I8 val

i16_unsafe¶
[Source]
fun box i16_unsafe()
: I16 val

Returns¶


A `NullablePointer` type can only be used with `structs`, and is only intended for output parameters (like in the example above) or for return types from C. You don't need to use a `NullablePointer` if you are only passing a `struct` as a regular input parameter.


args: Array[String] ref)
: (Option | SyntaxError)
=>
"""
--opt=foo => --opt has argument foo
--opt foo => --opt has argument foo, iff arg is required
"""
// Only split the token in two parts. If argument contains '=',
// and the token is of the form --opt=foo=bar, then targ will contain foo=bar
let parts = token.split("=", 2)
let name = try parts(0)? else "???" end
let targ = try parts(1)? else None end
match _option_with_name(name)
| let os: OptionSpec => _OptionParser.parse(os, targ, args)
| None => SyntaxError(name, "unknown long option")
end

fun _parse_short_options(
token: String,
args: Array[String] ref)


Parameters¶

i: USize val

Returns¶

A ?


fun ref _delete_prev_word() =>
"""
Delete the previous word.
"""
try
let old = _cur_pos

while (_cur_pos > 0) and (_edit((_cur_pos - 1).usize())? == ' ') do
_cur_pos = _cur_pos - 1
end

while (_cur_pos > 0) and (_edit((_cur_pos - 1).usize())? != ' ') do
_cur_pos = _cur_pos - 1
end

_edit.delete(_cur_pos, (old - _cur_pos).usize())
_refresh_line()
end

fun ref _tab() =>


: FileMode iso^

Returns¶

FileMode iso^

Public fields¶
var setuid: Bool val¶
[Source]
true if the SETUID bit is set.

var setgid: Bool val¶
[Source]
true if the SETGID bit is set.

var sticky: Bool val¶
[Source]
true if the sticky bit is set.


Public Functions¶
value¶
[Source]
fun box value()
: U32 val

Returns¶

U32 val

eq¶
[Source]
fun box eq(
that: FileMkdir val)
: Bool val

Parameters¶


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391


u32¶
[Source]
A random integer in [0, 2^32)
fun ref u32()
: U32 val

Returns¶

U32 val

u64¶
[Source]
A random integer in [0, 2^64)
fun ref u64()
: U64 val

Returns¶

U64 val


Bool val ?

ne¶
[Source]
fun box ne(
that: Lists[A] val)
: Bool val

Parameters¶

that: Lists[A] val

Returns¶

Bool val


572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591


### Examples

```pony
Iter[I64]([1; 2; 3].values())
.find({(x) => (x % 2) == 0 })
```
`2`

```pony
Iter[I64]([1; 2; 3; 4].values())
.find({(x) => (x % 2) == 0 }, 2)
```
`4`
"""
var c = n
for x in _iter do
if try f(x)? else false end then
if c == 1 then
return x
else


u32¶
[Source]
Create a generator for U32 values.
fun box u32(
min: U32 val = call,
max: U32 val = call)
: Generator[U32 val] box

Parameters¶

min: U32 val = call
max: U32 val = call

Returns¶

Generator[U32 val] box

u64¶
[Source]


Parameters¶

s: String box
offset: ISize val = 0
nth: USize val = 0

Returns¶

ISize val ?

rfind¶
[Source]
Return the index of n-th instance of s in the string starting from the
end. The offset represents the highest index to included in the search.
Raise an error if there is no n-th occurrence of s or s is empty.
fun box rfind(
s: String box,
offset: ISize val = call,


new val create()
: PrefixSpace val^

Returns¶

PrefixSpace val^

Public Functions¶
eq¶
[Source]
fun box eq(
that: PrefixSpace val)
: Bool val

Parameters¶

that: PrefixSpace val

Returns¶


692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131


When len is -1, all elements of sequence are pushed.
Does not remove elements from sequence.
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = List[String].from(["d"; "e"; "f"])
my_list.append(other_list)  // my_list is ["a"; "b"; "c"; "d"; "e"; "f"], other_list is unchanged

fun ref append(
seq: (ReadSeq[A] box & ReadElement[A^] box),
offset: USize val = 0,
len: USize val = call)
: None val

Parameters¶

seq: (ReadSeq[A] box & ReadElement[A^] box)
offset: USize val = 0
len: USize val = call

Returns¶


NetAuth¶
[Source]
primitive val NetAuth

Constructors¶
create¶
[Source]
new val create(
from: AmbientAuth val)
: NetAuth val^

Parameters¶


fun mmap_rw(): U64 => mmap_r() or mmap_w()
fun mmap_rx(): U64 => mmap_r() or mmap_x()
fun mmap_wx(): U64 => mmap_w() or mmap_x()
fun mmap_rwx(): U64 => mmap_r() or mmap_w() or mmap_x()

fun creat(): U64 => _id(0, 1 << 6)
fun fexecve(): U64 => _id(0, 1 << 7)
fun fsync(): U64 => _id(0, 1 << 8)
fun ftruncate(): U64 => _id(0, 1 << 9)
fun lookup(): U64 => _id(0, 1 << 10)
fun fchdir(): U64 => _id(0, 1 << 11)
fun fchflags(): U64 => _id(0, 1 << 12)
fun chflagsat(): U64 => fchflags() or lookup()
fun fchmod(): U64 => _id(0, 1 << 13)
fun fchmodat(): U64 => fchmod() or lookup()
fun fchown(): U64 => _id(0, 1 << 14)
fun fchownat(): U64 => fchown() or lookup()
fun fcntl(): U64 => _id(0, 1 << 15)
fun flock(): U64 => _id(0, 1 << 16)
fun fpathconf(): U64 => _id(0, 1 << 17)


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

u16_unsafe¶
[Source]
fun box u16_unsafe()
: U16 val

Returns¶

U16 val

u32_unsafe¶
[Source]


FormatBinaryBare¶
[Source]
primitive val FormatBinaryBare is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


A

eq¶
[Source]
fun box eq(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶

Bool val

ne¶
[Source]


Array[NetAddress val] iso^

broadcast_ip4¶
[Source]
Link-local IP4 broadcast address.
fun box broadcast_ip4(
auth: DNSAuth val,
service: String val)
: Array[NetAddress val] iso^

Parameters¶

auth: DNSAuth val
service: String val

Returns¶

Array[NetAddress val] iso^


fun box so_max_pacing_rate()
: I32 val

Returns¶

I32 val

so_multipoint¶
[Source]
fun box so_multipoint()
: I32 val

Returns¶

I32 val

so_netsvc_marking_level¶
[Source]


# Divide by zero in Pony

In Pony, *integer division by zero results in zero*. That's right,

```pony
let x = I64(1) / I64(0)
```

results in `0` being assigned to `x`. Baffling right? Well, yes and no. From a mathematical standpoint, it is very much baffling. From a practical standpoint, it is very much not.

While Pony has [Partial division](/expressions/arithmetic.md#partial-and-checked-arithmetic):

```pony
let x =
try
I64(1) /? I64(0)
else
// handle division by zero
end
```


envs: (Array[String val] box | None val)
prefix: String val = ""
squash: Bool val = false

Returns¶

HashMap[String val, String val, HashEq[String val] val] val

eq¶
[Source]
fun box eq(
that: EnvVars val)
: Bool val

Parameters¶

that: EnvVars val


(I16 val , I16 val) ?

fld_partial¶
[Source]
fun box fld_partial(
y: I16 val)
: I16 val ?

Parameters¶

y: I16 val

Returns¶

I16 val ?

mod_partial¶
[Source]


fun box so_linger_sec()
: I32 val

Returns¶

I32 val

so_linkinfo¶
[Source]
fun box so_linkinfo()
: I32 val

Returns¶

I32 val

so_listenincqlen¶
[Source]


Promise[Array[A] val] tag

select¶
[Source]
Return a promise that is fulfilled when either promise is fulfilled,
resulting in a tuple of its value and the other promise.
fun tag select(
p: Promise[A] tag)
: Promise[(A , Promise[A] tag)] tag

Parameters¶

p: Promise[A] tag

Returns¶

Promise[(A , Promise[A] tag)] tag


: String val

Returns¶

String val

print_help¶
[Source]
Prints the help message to an OutStream.
fun box print_help(
os: OutStream tag)
: None val

Parameters¶

os: OutStream tag

Returns¶


fun box add_partial(
y: I128 val)
: I128 val ?

Parameters¶

y: I128 val

Returns¶

I128 val ?

sub_partial¶
[Source]
fun box sub_partial(
y: I128 val)
: I128 val ?

Parameters¶


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


(USize val , USize val) ?

shl¶
[Source]
fun box shl(
y: USize val)
: USize val

Parameters¶

y: USize val

Returns¶

USize val

shr¶
[Source]


"""
Private helper for `reverse`, recursively working with `ListNode`s.
"""
try acc.unshift(ln()?) end

try
_reverse(ln.next() as this->ListNode[A], acc)
else
acc
end

fun contains[B: (A & HasEq[A!] #read) = A](a: box->B): Bool =>
"""
Returns `true` if the `List` contains the provided element, otherwise returns `false`.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let contains_b = my_list.contains[String]("b") // true
```
"""


data: I128 val

Returns¶

None val

write¶
[Source]
Write a ByteSeq to the buffer.
fun ref write(
data: (String val | Array[U8 val] val))
: None val

Parameters¶

data: (String val | Array[U8 val] val)

Returns¶


primitive FetchIssue
fun apply(number: I64, repo: Repository): Promise[Issue] =>
repo.get_issue(number)

primitive PrintIssueTitle
fun apply(out: OutStream, issue: Promise[Issue]) =>
// O NO! We can't print the title
// We don't have an issue, we have a promise for an issue
```

Take a look at what happens in the example, when we get to
`PrintIssueTitle`, we can't print anything because we "don't have anything".
In order to print the issue title, we need an `Issue` not a
`Promise[Issue]`.

We could solve this by doing something like this:

```pony
primitive PrintIssueTitle


fun box fld(
y: U128 val)
: U128 val

Parameters¶

y: U128 val

Returns¶

U128 val

fldc¶
[Source]
fun box fldc(
y: U128 val)
: (U128 val , Bool val)

Parameters¶


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


fun box ipv6_prefer_src_cga()
: I32 val

Returns¶

I32 val

ipv6_prefer_src_coa¶
[Source]
fun box ipv6_prefer_src_coa()
: I32 val

Returns¶

I32 val

ipv6_prefer_src_home¶
[Source]


test: ITest box
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val

assert_no_error¶
[Source]
Assert that the gived test function does not throw an error when run.
fun box assert_no_error(
test: ITest box,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val

Parameters¶


fun assert_array_eq_unordered[A: (Equatable[A] #read & Stringable #read)](
expect: ReadSeq[A],
actual: ReadSeq[A],
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>
"""
Assert that the contents of the 2 given ReadSeqs are equal ignoring order.
"""
try
let missing = Array[box->A]
let consumed = Array[Bool].init(false, actual.size())
for e in expect.values() do
var found = false
var i: USize = -1
for a in actual.values() do
i = i + 1
if consumed(i)? then continue end


issue.next[None](PrintIssueTitle~apply(env.out))

it can be hard to follow what is going on. We can only tell what is
happening because we gave PrintIssueTitle a very misleading name; it
doesn't print an issue title.
flatten_next addresses the problem of "we want the Issue, not the
intermediate Promise". flatten_next takes an intermediate promise and
unwraps it into the fulfilled type. You get to write your promise chain
without having to worry about intermediate promises.
Updated to use flatten_next, our API example becomes:
actor Main
new create(env: Env) =>
let repo: Promise[Repository] =
GitHub("my token").get_repo("ponylang/ponyc")

let issue = Promise[Issue] =
repo.flatten_next[Issue](FetchIssue~apply(1))

issue.next[None](PrintIssueTitle~apply(env.out))


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


y: U8 val

Returns¶

Bool val

lt¶
[Source]
fun box lt(
y: U8 val)
: Bool val

Parameters¶

y: U8 val

Returns¶


fun box le(
y: I128 val)
: Bool val

Parameters¶

y: I128 val

Returns¶

Bool val

ge¶
[Source]
fun box ge(
y: I128 val)
: Bool val

Parameters¶


"""
Bright yellow background.
"""
"\x1B[103m"

fun bright_blue_bg(): String =>
"""
Bright blue background.
"""
"\x1B[104m"

fun bright_magenta_bg(): String =>
"""
Bright magenta background.
"""
"\x1B[105m"

fun bright_cyan_bg(): String =>
"""
Bright cyan background.


has_next¶
[Source]
Indicates whether there are any nodes remaining in the iterator.
fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Return the next node in the iterator, advancing the iterator by one element.
Order of return is determined by reverse argument during creation.
fun ref next()
: N ?

Returns¶


alt: Bool val
shift: Bool val

Returns¶

None val

size¶
[Source]
fun ref size(
rows: U16 val,
cols: U16 val)
: None val

Parameters¶

rows: U16 val
cols: U16 val


fun box tcp_saved_syn()
: I32 val

Returns¶

I32 val

tcp_save_syn¶
[Source]
fun box tcp_save_syn()
: I32 val

Returns¶

I32 val

tcp_sendmoreacks¶
[Source]


fun box exattr_delete()
: U64 val

Returns¶

U64 val

exattr_get¶
[Source]
fun box exattr_get()
: U64 val

Returns¶

U64 val

exattr_list¶
[Source]


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511


y: I64 val

Returns¶

I64 val

op_or¶
[Source]
fun box op_or(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶


fun box tipc_link_state()
: I32 val

Returns¶

I32 val

tipc_low_importance¶
[Source]
fun box tipc_low_importance()
: I32 val

Returns¶

I32 val

tipc_max_bearer_name¶
[Source]


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


let len = (search_len + data.find(byte, offset)? + 1) - offset
search_len = 0
return len
end

search_len = search_len + (data.size() - offset)

if not node.has_next() then
break
end

node = node.next() as ListNode[(Array[U8] val, USize)]
end

error

fun ref _search_length(): USize ? =>
"""
Get the length of a pending line. Raise an error if there is no pending
line.


The number of elements that have been added to the ring.
"""
_write

fun space(): USize =>
"""
The available space in the ring.
"""
_mod + 1

fun apply(i: USize): this->A ? =>
"""
Get the i-th element from the ring. If the i-th element has not yet been
added or is no longer available, this will raise an error.
"""
if (i >= _write) or ((_write - i) > space()) then
error
end

_array(i and _mod)?


fun box sctp_data_frag_mask()
: I32 val

Returns¶

I32 val

sctp_data_last_frag¶
[Source]
fun box sctp_data_last_frag()
: I32 val

Returns¶

I32 val

sctp_data_middle_frag¶
[Source]


[Source]
new val create()
: Nil[A] val^

Returns¶

Nil[A] val^

Public Functions¶
size¶
[Source]
Returns the size of the list.
fun box size()
: USize val

Returns¶

USize val


fun box ip_fw_nat_get_log()
: I32 val

Returns¶

I32 val

ip_fw_resetlog¶
[Source]
fun box ip_fw_resetlog()
: I32 val

Returns¶

I32 val

ip_fw_table_add¶
[Source]


fun box mrt_del_bw_upcall()
: I32 val

Returns¶

I32 val

mrt_del_mfc¶
[Source]
fun box mrt_del_mfc()
: I32 val

Returns¶

I32 val

mrt_del_vif¶
[Source]


fun box so_donttrunc()
: I32 val

Returns¶

I32 val

so_error¶
[Source]
fun box so_error()
: I32 val

Returns¶

I32 val

so_exclusiveaddruse¶
[Source]


fun box so_conditional_accept()
: I32 val

Returns¶

I32 val

so_connect_time¶
[Source]
fun box so_connect_time()
: I32 val

Returns¶

I32 val

so_debug¶
[Source]


fun box tcp_sendmoreacks()
: I32 val

Returns¶

I32 val

tcp_syncnt¶
[Source]
fun box tcp_syncnt()
: I32 val

Returns¶

I32 val

tcp_s_data_in¶
[Source]


fun apply(h: TestHelper) =>
PonyCheck.for_all[U8](recover Generators.unit[U8](0) end, h)(
{(u, h) =>
h.assert_eq(u, 0)
consume u
})
```
"""
ForAll[T](gen, h)

fun for_all2[T1, T2](
gen1: Generator[T1] val,
gen2: Generator[T2] val,
h: TestHelper)
: ForAll2[T1, T2]
=>
ForAll2[T1, T2](gen1, gen2, h)

fun for_all3[T1, T2, T3](


Bool val


Public fields¶
var ponymaxthreads: U32 val¶
[Source]
Use N scheduler threads. Defaults to the number of cores (not hyperthreads)
available.
This can't be larger than the number of cores available.

var ponyminthreads: U32 val¶
[Source]
Minimum number of active scheduler threads allowed.
Defaults to 0, meaning that all scheduler threads are allowed to be
suspended when no work is available.
This can't be larger than --ponymaxthreads if provided, or the physical
cores available.

var ponynoscale: Bool val¶
[Source]
Don't scale down the scheduler threads.
See --ponymaxthreads on how to specify the number of threads explicitly.


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


if sum >= _yield_after_reading then
// If we've read _yield_after_reading bytes
// yield and read again later.
_read_again()
_reading = false
return
end

_read_buf_size()

// Read as much data as possible.
let len = @pony_os_recv(
_event,
_read_buf.cpointer(_read_buf_offset),
_read_buf.size() - _read_buf_offset) ?

if len == 0 then
// Would block, try again later.
// this is safe because asio thread isn't currently subscribed
// for a read event so will not be writing to the readable flag


(Cons[A] val | Nil[A] val)


y: U64 val

Returns¶

(U64 val , U64 val)

rem_unsafe¶
[Source]
fun box rem_unsafe(
y: U64 val)
: U64 val

Parameters¶

y: U64 val

Returns¶


Returns¶

String val

apply¶
[Source]
fun ref apply(
h: TestHelper val)
: None val ?

Parameters¶

h: TestHelper val

Returns¶

None val ?


fun box mod_partial(
y: I8 val)
: I8 val ?

Parameters¶

y: I8 val

Returns¶

I8 val ?

shl¶
[Source]
fun box shl(
y: U8 val)
: I8 val

Parameters¶


(let arg1, let arg2) = consume arg
fn(consume arg1, consume arg2)
})

fun map3[T1, T2, T3, T4](
gen1: Generator[T1],
gen2: Generator[T2],
gen3: Generator[T3],
fn: {(T1, T2, T3): T4^})
: Generator[T4]
=>
"""
Convenience combinator for mapping 3 generators into 1.
"""
Generators.zip3[T1, T2, T3](gen1, gen2, gen3)
.map[T4]({(arg) =>
(let arg1, let arg2, let arg3) = consume arg
fn(consume arg1, consume arg2, consume arg3)
})


Peek at a little-endian I128.
fun box peek_i128_le(
offset: USize val = 0)
: I128 val ?

Parameters¶

offset: USize val = 0

Returns¶

I128 val ?

peek_f32_be¶
[Source]
Peek at a big-endian F32.
fun box peek_f32_be(
offset: USize val = 0)
: F32 val ?


```bash
clang -fPIC -Wall -Wextra -O3 -g -MM jch.c >jch.d
clang -fPIC -Wall -Wextra -O3 -g  -c -o jch.o jch.c
clang -shared -lm -o libjch.dylib jch.o
```

The Pony code to use this new C library is just like the code we've already seen for using C libraries.

```pony
"""
This is an example of Pony integrating with native code via the built-in FFI
support
"""

use "lib:jch"
use "collections"
use @jch_chash[I32](hash: U64, bucket_size: U32)

actor Main


y: U64 val

Returns¶

(U64 val , Bool val)

remc¶
[Source]
fun box remc(
y: U64 val)
: (U64 val , Bool val)

Parameters¶

y: U64 val

Returns¶


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


Returns¶

F64 val

acos¶
[Source]
fun box acos()
: F64 val

Returns¶

F64 val

asin¶
[Source]
fun box asin()
: F64 val


y: I8 val

Returns¶

Bool val

lt¶
[Source]
fun box lt(
y: I8 val)
: Bool val

Parameters¶

y: I8 val

Returns¶


FileStream¶
[Source]
Asynchronous access to a File object. Wraps file operations print, write,
printv and writev. The File will be disposed through File._final.
actor tag FileStream is
OutStream tag

Implements¶

OutStream tag

Constructors¶


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231


Example:
let original: String = "name,job;department"
let delimiter: String = ".,;"
let split_array: Array[String] = original.split(delimiter)
env.out.print("OUTPUT:")
for value in split_array.values() do
env.out.print(value)
end

// OUTPUT:
// name
// job
// department

Adjacent delimiters result in a zero length entry in the array. For
example, "1,,2".split(",") => ["1", "", "2"].
If you want to split the string with the entire delimiter string delim,
use split_by.
fun box split(
delim: String val = "


Public fields¶
let root: AmbientAuth val¶
[Source]
The root capability.

let input: InputStream tag¶
[Source]
Stdin represented as an actor.

let out: OutStream tag¶
[Source]
Stdout

let err: OutStream tag¶
[Source]
Stderr

let args: Array[String val] val¶


I16 val

op_and¶
[Source]
fun box op_and(
y: I16 val)
: I16 val

Parameters¶

y: I16 val

Returns¶

I16 val

op_or¶
[Source]


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


# Explaining why

That table will seem totally natural to you, eventually. But probably not yet. To help it seem natural, let's walk through each cell in the table and explain why it is the way it is.


"""
Nil[A]

fun cons(h: val->A, t: List[A]): List[A] =>
"""
Returns a list that has h as a head and t as a tail.
"""
Cons[A](h, t)

fun apply(arr: Array[val->A]): List[A] =>
"""
Builds a new list from an Array
"""
this.from(arr.values())

fun from(iter: Iterator[val->A]): List[A] =>
"""
Builds a new list from an iterator
"""
var l: List[A] = Nil[A]


Integer[A: Integer[A] val]¶
[Source]
trait val Integer[A: Integer[A] val] is
Real[A] val

Implements¶

Real[A] val

Constructors¶
create¶
[Source]


352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371


Parameters¶

y: ISize val

Returns¶

ISize val

mod_unsafe¶
[Source]
fun box mod_unsafe(
y: ISize val)
: ISize val

Parameters¶

y: ISize val

Returns¶


Public Functions¶
name¶
[Source]
fun box name()
: String val

Returns¶

String val

config¶
[Source]
fun box config()
: BenchConfig val

Returns¶

BenchConfig val


fun is_null_terminated(): Bool =>
"""
Return true if the string is null-terminated and safe to pass to an FFI
function that doesn't accept a size argument, expecting a null-terminator.
This method checks that there is a null byte just after the final position
of populated bytes in the string, but does not check for other null bytes
which may be present earlier in the content of the string.
If you need a null-terminated copy of this string, use the clone method.
"""
(_alloc > 0) and (_alloc != _size) and (_ptr._apply(_size) == 0)

fun utf32(offset: ISize): (U32, U8) ? =>
"""
Return a UTF32 representation of the character at the given offset and the
number of bytes needed to encode that character. If the offset does not
point to the beginning of a valid UTF8 encoding, return 0xFFFD (the unicode
replacement character) and a length of one. Raise an error if the offset is
out of bounds.
"""


"""
if _size == 0 then
return consume b
end

if b.size() == 0 then
return consume this
end

(let unchoppable, let a_left) =
if (_size == _alloc) and (cpointer(_size) == b.cpointer()) then
(true, true)
elseif (b.size() == b.space()) and (b.cpointer(b.size()) == cpointer())
then
(true, false)
else
(false, false)
end

if not unchoppable then


Generate a USize in closed interval [min, max]
(default: [min_value, max_value]).

Behavior is undefined if `min` > `max`.
"""
u64(min.u64(), max.u64()).usize()

fun ref i8(min: I8 = I8.min_value(), max: I8 = I8.max_value()): I8 =>
"""
Generate a I8 in closed interval [min, max]
(default: [min_value, max_value]).

Behavior is undefined if `min` > `max`.
"""
min + u8(0, (max - min).u8()).i8()

fun ref i16(min: I16 = I16.min_value(), max: I16 = I16.max_value()): I16 =>
"""
Generate a I16 in closed interval [min, max]
(default: [min_value, max_value]).


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


USize val

f32¶
[Source]
fun box f32()
: F32 val

Returns¶

F32 val

f64¶
[Source]
fun box f64()
: F64 val

Returns¶


92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111


Signals package¶
The Signals package provides support for handling Unix style signals.
For each signal that you want to handle, you need to create a SignalHandler
and a corresponding SignalNotify object. Each SignalHandler runs as it own
actor and upon receiving the signal will call its corresponding
SignalNotify's apply method.
Example program¶
The following program will listen for the TERM signal and output a message to
standard out if it is received.
use "signals"

actor Main
new create(env: Env) =>


options

fun _all_options_fill(options: Array[OptionSpec box]) =>
match _parent
| let p: CommandHelp => p._all_options_fill(options)
end
for o in _spec.options().values() do
options.push(o)
end

primitive _Columns
fun indent(w: Writer, n: USize) =>
var i = n
while i > 0 do
w.write(" ")
i = i - 1
end

fun write(w: Writer, cols: Array[(USize,String,String)]) =>
var widest: USize = 0


y: I16 val

Returns¶

(I16 val , Bool val)

remc¶
[Source]
fun box remc(
y: I16 val)
: (I16 val , Bool val)

Parameters¶

y: I16 val

Returns¶


# Naming rules

All names in Pony, such as type names, method names, and variable names may contain only [__ASCII__](https://en.wikipedia.org/wiki/ASCII) characters.

In fact all elements of Pony code are required to be ASCII, except string literals, which happily accept any kind of bytes directly from the source file, be it `UTF-8` encoded or `ISO-8859-2` and represent them in their encoded form.

A Pony type, whether it's a class, actor, trait, interface, primitive, or type alias, must start with an uppercase letter. After an underscore for private or special _methods_ (behaviors, constructors, and functions), any method or variable, including parameters and fields, must start with a lowercase letter. In all cases underscores in a row or at the end of a name are not allowed, but otherwise, any combination of letters and numbers is legal.

In fact, numbers may use single underscores inside as a separator too!

Only variable names can end in primes (`'`).


u32_unsafe¶
fun box u32_unsafe()
: U32 val

Returns¶

U32 val

u64_unsafe¶
fun box u64_unsafe()
: U64 val

Returns¶

U64 val

ulong_unsafe¶
fun box ulong_unsafe()


[Source]
Called when we have failed to connect to all possible addresses for the
server. At this point, the connection will never be established.
It is expected to implement proper error handling. You need to opt in to
ignoring errors, which can be implemented like this:
fun ref connect_failed(conn: TCPConnection ref) =>
None

fun ref connect_failed(
conn: TCPConnection ref)
: None val

Parameters¶

conn: TCPConnection ref

Returns¶

None val


name': String val
descr': String val = ""
default': (U64 val | None val) = reference

Returns¶

ArgSpec val^

f64¶
[Source]
Creates an Arg with a F64 typed value that can be used like
<cmd> 1.039
to yield an arg value like
cmd.arg("ratio").f64() == F64(1.039).
new val f64(
name': String val,
descr': String val = "",
default': (F64 val | None val) = reference)
: ArgSpec val^


I16 val

i32_unsafe¶
[Source]
fun box i32_unsafe()
: I32 val

Returns¶

I32 val

i64_unsafe¶
[Source]
fun box i64_unsafe()
: I64 val

Returns¶


Dice¶
[Source]
A simple dice roller.
class ref Dice

Constructors¶
create¶
[Source]
Initialise with a random number generator.
new ref create(
from: Random ref)
: Dice ref^


_set(0, 0)
else
_size = len
_alloc = _size + 1
_ptr = Pointer[U8]._alloc(_alloc)
str._copy_to(_ptr, _alloc)
end

new copy_cstring(str: Pointer[U8] box) =>
"""
Create a string by copying a null-terminated C string. Note that
the scan is unbounded; the pointed to data must be null-terminated
within the allocated array to preserve memory safety. If a null
pointer is given then an empty string is returned.
"""
if str.is_null() then
_size = 0
_alloc = 1
_ptr = Pointer[U8]._alloc(_alloc)
_set(0, 0)


yield_after_reading: USize val = 16384
yield_after_writing: USize val = 16384

Returns¶

TCPListener tag^

ip6¶
[Source]
Listens for IPv6 connections.
new tag ip6(
auth: TCPListenAuth val,
notify: TCPListenNotify iso,
host: String val = "",
service: String val = "0",
limit: USize val = 0,
read_buffer_size: USize val = 16384,
yield_after_reading: USize val = 16384,
yield_after_writing: USize val = 16384)


use "pony_check"

class ListReverseProperty is Property1[List[USize]]
fun name(): String => "list/reverse"

fun gen(): Generator[List[USize]] =>
Generators.list_of[USize](Generators.usize())

fun property(arg1: List[USize], ph: PropertyHelper) =>
ph.array_eq[USize](arg1, arg1.reverse().reverse())
```


new val from[B: (Number & Real[B] val)](a: B)
new val min_value()
new val max_value()

fun add(y: A): A => this + y
fun sub(y: A): A => this - y
fun mul(y: A): A => this * y
fun div(y: A): A =>
"""
Integer division, rounded towards zero.
"""
this / y

fun divrem(y: A): (A, A) => (this / y, this % y)
fun rem(y: A): A =>
"""
Calculate the remainder after integer division, rounded towards zero (`div`).

The result has the sign of the dividend.
"""


fun box add(
y: U32 val)
: U32 val

Parameters¶

y: U32 val

Returns¶

U32 val

sub¶
[Source]
fun box sub(
y: U32 val)
: U32 val

Parameters¶


452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471


132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


fun box rose_t2()
: I32 val

Returns¶

I32 val

rose_t3¶
[Source]
fun box rose_t3()
: I32 val

Returns¶

I32 val

scm_hci_raw_direction¶
[Source]


fun gen3(): Generator[T3] => _gen3
fun gen4(): Generator[T4] => _gen4
fun ref property4(arg1: T1, arg2: T2, arg3: T3, arg4: T4, h: PropertyHelper) ? =>
prop(consume arg1, consume arg2, consume arg3, consume arg4, h)?
end
).apply(_helper)?


fun ref _cancel() =>
"""
Remove the timer from any list.
"""
_node.remove()
_notify.cancel(this)

fun ref _get_node(): ListNode[Timer] =>
"""
Returns the list node pointing to the timer. Used to schedule the timer in
a queue.
"""
_node

fun ref _slop(bits: USize) =>
"""
Apply slop bits to the expiration time and interval. This reduces the
precision by the given number of bits, effectively quantizing time.
"""
_expiration = _expiration >> bits.u64()


while i < _size do
try
(let c, let len) = utf32(i.isize())?
if not chars.contains(c) then
break
end
i = i + len.usize()
else
break
end
end

if i > 0 then
delete(0, i)
end
end

fun iso _append(s: String box): String iso^ =>
let len = _size + s._size
reserve(len)


y: F32 val

Returns¶

F32 val

mul_unsafe¶
fun box mul_unsafe(
y: F32 val)
: F32 val

Parameters¶

y: F32 val

Returns¶

F32 val


prevents this.
be set_multicast_loopback(
loopback: Bool val)

Parameters¶

loopback: Bool val

set_multicast_ttl¶
[Source]
Set the TTL for multicast sends. Defaults to 1.
be set_multicast_ttl(
ttl: U8 val)

Parameters¶

ttl: U8 val


Public Functions¶
apply¶
[Source]
fun box apply()
: String val

Returns¶

String val

eq¶
[Source]
fun box eq(
that: ASCIILettersUpper val)
: Bool val

Parameters¶


We can see that it makes more sense for the unary operator to be applied before either infix as it only acts on a single number in the expression so it is never ambiguous.

Unary operators can also be applied to parentheses and act on the result of all operations in those parentheses prior to applying any infix operators outside the parentheses:

```pony
1 + -(2 * -3)  // 7
```


value: this->A!)
: HashSet[this->A!, K] ref^

Parameters¶

value: this->A!

Returns¶

HashSet[this->A!, K] ref^

sub[optional K: HashFunction[this->A!] val]¶
[Source]
Remove a value from the set.
fun box sub[optional K: HashFunction[this->A!] val](
value: box->this->A!)
: HashSet[this->A!, K] ref^

Parameters¶


# Serialisation

Pony provides a built-in mechanism for serialising and deserialising objects so that they can be passed between Pony processes. Serialisation takes an object and turns it into an array of bytes that can be used to send the object to another process by, for example, writing it to a TCP stream. Deserialisation takes an array of bytes and turns them into a Pony object.

Pony uses an intermediate object type called `Serialised` to represent a serialised object. A `Serialised` object can be created in one of two ways:

* calling the `create(...)` constructor with the `SerialiseAuth` authority and the object to serialize
* calling the `input(...)` constructor with the `DeserialiseAuth` authority and an `Array[U8]` that represents the object to deserialise. This intermediate object can then be used to either:

* generate an `Array[U8]` that represents the object by calling the `output(...)` method with the `OutputSerialisedAuth` authority, or
* generate a deserialised object by calling the `apply(...)` method with the `InputSerialisedAuth` authority

This program serialises and deserialise an object, and checks that the fields of the original object are the same as the fields of the deserialised object.

```pony
use "serialise"

class Foo is Equatable[Foo box]
let _s: String
let _u: U32


Signed¶
[Source]
type Signed is
(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val)

Type Alias For¶

(I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val)


i = i - 1
end
error

fun contains(s: String box, offset: ISize = 0, nth: USize = 0): Bool =>
"""
Returns true if contains s as a substring, false otherwise.
"""
var i = offset_to_index(offset)
var steps = nth + 1

while i < _size do
var j: USize = 0

let same = while j < s._size do
if _ptr._apply(i + j) != s._ptr._apply(j) then
break false
end
j = j + 1
true


532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551


fun box u128()
: U128 val

Returns¶

U128 val

ulong¶
[Source]
fun box ulong()
: ULong val

Returns¶

ULong val

usize¶
[Source]


that: box->A

Returns¶

Bool val


Parameters¶

y: ISize val

Returns¶

Bool val

gt¶
[Source]
fun box gt(
y: ISize val)
: Bool val

Parameters¶

y: ISize val

Returns¶


fun box tcpopt_window()
: I32 val

Returns¶

I32 val

tcp_ca_name_max¶
[Source]
fun box tcp_ca_name_max()
: I32 val

Returns¶

I32 val

tcp_ccalgoopt¶
[Source]


Parameters¶

y: ILong val

Returns¶

ILong val ?

mul_partial¶
[Source]
fun box mul_partial(
y: ILong val)
: ILong val ?

Parameters¶

y: ILong val

Returns¶


expect: ReadSeq[A] box,
actual: ReadSeq[A] box,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val

Parameters¶

expect: ReadSeq[A] box
actual: ReadSeq[A] box
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val

long_test¶
[Source]


U8 val

max¶
[Source]
fun box max(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

addc¶
[Source]


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


"""
Calculates the modulo of this number after floored division by `y`.

*Unsafe Operation.*

If y is 0, the result is undefined.
If the operation overflows, the result is undefined.
"""

fun add_partial(y: A): A ?
"""
Add y to this number.

If the operation overflows this function errors.
"""

fun sub_partial(y: A): A ?
"""
Subtract y from this number.


fun box so_proxyusr()
: I32 val

Returns¶

I32 val

so_randomport¶
[Source]
fun box so_randomport()
: I32 val

Returns¶

I32 val

so_rcvbuf¶
[Source]


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

compare¶
[Source]
fun box compare(
that: U8 val)
: (Less val | Equal val | Greater val)

Parameters¶

that: U8 val

Returns¶


F32 val^

e¶
[Source]
new val e()
: F32 val^

Returns¶

F32 val^

from_bits¶
[Source]
new val from_bits(
i: U32 val)
: F32 val^

Parameters¶


serialise.pony

1
2
3
4
5
6
7
8
9
10
11


USize val

f32_unsafe¶
[Source]
fun box f32_unsafe()
: F32 val

Returns¶

F32 val

f64_unsafe¶
[Source]
fun box f64_unsafe()
: F64 val

Returns¶


fun box tcp_connection_info()
: I32 val

Returns¶

I32 val

tcp_cookie_in_always¶
[Source]
fun box tcp_cookie_in_always()
: I32 val

Returns¶

I32 val

tcp_cookie_max¶
[Source]


update¶
[Source]
Change the i-th element, raising an error if the index is out of bounds.
fun ref update(
i: USize val,
value: A)
: A^ ?

Parameters¶

i: USize val
value: A

Returns¶

A^ ?

insert¶
[Source]


F32 val

log10¶
[Source]
fun box log10()
: F32 val

Returns¶

F32 val

logb¶
[Source]
fun box logb()
: F32 val

Returns¶


fun encode(value: U32): (USize, U8, U8, U8, U8) =>
"""
Encode the code point into UTF-8. It returns a tuple with the size of the
encoded data and then the data.
"""
if value < 0x80 then
(1, value.u8(), 0, 0, 0)
elseif value < 0x800 then
( 2,
((value >> 6) or 0xC0).u8(),
((value and 0x3F) or 0x80).u8(),
0,
0
)
elseif value < 0xD800 then
( 3,
((value >> 12) or 0xE0).u8(),
(((value >> 6) and 0x3F) or 0x80).u8(),
((value and 0x3F) or 0x80).u8(),
0


Bool val

ne¶
[Source]
fun box ne(
that: TCPConnectAuth val)
: Bool val

Parameters¶

that: TCPConnectAuth val

Returns¶

Bool val


# Primitives

A __primitive__ is similar to a __class__, but there are two critical differences:

1. A __primitive__ has no fields.
2. There is only one instance of a user-defined __primitive__.

Having no fields means primitives are never mutable. Having a single instance means that if your code calls a constructor on a __primitive__ type, it always gets the same result back (except for built-in "machine word" primitives, covered below).


fun box u32()
: U32 val

Returns¶

U32 val

u64¶
[Source]
fun box u64()
: U64 val

Returns¶

U64 val

u128¶
[Source]


fun box dccp_nr_pkt_types()
: I32 val

Returns¶

I32 val

dccp_service_list_max_len¶
[Source]
fun box dccp_service_list_max_len()
: I32 val

Returns¶

I32 val

dccp_single_opt_maxlen¶
[Source]


define __JCH_H_

extern "C"
{
int32_t jch_chash(uint64_t key, uint32_t num_buckets);
}


runtime_options.pony

1
2
3
4
5
6
7
8
9
10
11


fun fld_unsafe(y: I8): I8 =>
_SignedUnsafeArithmetic.fld_unsafe[I8, U8](this, y)

fun mod(y: I8): I8 =>
_SignedArithmetic.mod[I8, U8](this, y)

fun mod_unsafe(y: I8): I8 =>
_SignedUnsafeArithmetic.mod_unsafe[I8, U8](this, y)

fun addc(y: I8): (I8, Bool) =>
@"llvm.sadd.with.overflow.i8"(this, y)

fun subc(y: I8): (I8, Bool) =>
@"llvm.ssub.with.overflow.i8"(this, y)

fun mulc(y: I8): (I8, Bool) =>
@"llvm.smul.with.overflow.i8"(this, y)

fun divc(y: I8): (I8, Bool) =>


[Source]
fun box sub(
y: ILong val)
: ILong val

Parameters¶

y: ILong val

Returns¶

ILong val

mul¶
[Source]
fun box mul(
y: ILong val)
: ILong val


A

divrem¶
[Source]
fun box divrem(
y: A)
: (A , A)

Parameters¶

y: A

Returns¶

(A , A)

rem¶
[Source]


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411


```
"""
fun apply(a: A): A^ =>
"""
Sort the given seq.
"""
try _sort(a, 0, a.size().isize() - 1)? end
a

fun _sort(a: A, lo: ISize, hi: ISize) ? =>
if hi <= lo then return end
// choose outermost elements as pivots
if a(lo.usize())? > a(hi.usize())? then _swap(a, lo, hi)? end
(var p, var q) = (a(lo.usize())?, a(hi.usize())?)
// partition according to invariant
(var l, var g) = (lo + 1, hi - 1)
var k = l
while k <= g do
if a(k.usize())? < p then
_swap(a, k, l)?


232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171


PrefixDefault¶
[Source]
primitive val PrefixDefault is
PrefixSpec val

Implements¶

PrefixSpec val

Constructors¶
create¶
[Source]


TCPConnection¶
[Source]
A TCP connection. When connecting, the Happy Eyeballs algorithm is used.
The following code creates a client that connects to port 8989 of
the local host, writes "hello world", and listens for a response,
which it then prints.
use "net"

class MyTCPConnectionNotify is TCPConnectionNotify
let _out: OutStream

new create(out: OutStream) =>
_out = out


option_name: I32 val,
option_max_size: USize val = 4)
: (U32 val , Array[U8 val] iso^)

Parameters¶

level: I32 val
option_name: I32 val
option_max_size: USize val = 4

Returns¶

(U32 val , Array[U8 val] iso^)

getsockopt_u32¶
[Source]
Wrapper for TCP sockets to the getsockopt(2) system call where
the kernel's returned option value is a C uint32_t type / Pony
type U32.


(Less val | Equal val | Greater val)


ttl: U8 val)
: U32 val

Parameters¶

ttl: U8 val

Returns¶

U32 val

set_so_broadcast¶
[Source]
Wrapper for the FFI call setsockopt(fd, SOL_SOCKET, SO_BROADCAST, ...)
fun ref set_so_broadcast(
state: Bool val)
: U32 val

Parameters¶


A

atan2¶
[Source]
fun box atan2(
y: A)
: A

Parameters¶

y: A

Returns¶

A

acosh¶
[Source]


prop: {(T1, T2, PropertyHelper) ?}[T1, T2] val

Returns¶

None val ?


ASCIIAllWithNUL val^

Public Functions¶
apply¶
[Source]
fun box apply()
: String val

Returns¶

String val

eq¶
[Source]
fun box eq(
that: ASCIIAllWithNUL val)
: Bool val


is a new empty string.
Both strings are isolated and mutable, as they do not share memory.
The operation does not allocate a new string pointer nor copy elements.
fun iso chop(
split_point: USize val)
: (String iso^ , String iso^)

Parameters¶

split_point: USize val

Returns¶

(String iso^ , String iso^)

unchop¶
[Source]
Unchops two iso strings to return the original string they were chopped
from. Both input strings are isolated and mutable and were originally


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311


h: TestHelper val)
: None val

Parameters¶

h: TestHelper val

Returns¶

None val

label¶
fun box label()
: String val

Returns¶

String val


fun box tipc_sock_recvq_depth()
: I32 val

Returns¶

I32 val

tipc_src_droppable¶
[Source]
fun box tipc_src_droppable()
: I32 val

Returns¶

I32 val

tipc_subscr_timeout¶
[Source]


use bar = "bar"
use foo = "foo"

actor Main is TestList
new create(env: Env) =>
PonyTest(env, this)

new make() =>
None

fun tag tests(test: PonyTest) =>
bar.Main.make().tests(test)
foo.Main.make().tests(test)

Aggregate test classes may themselves be aggregated. Every test list class may
contain any combination of its own tests and aggregated lists.
Long tests¶
Simple tests run within a single function. When that function exits, either
returning or raising an error, the test is complete. This is not viable for
tests that need to use actors.


fun box sctp_ecn_supported()
: I32 val

Returns¶

I32 val

sctp_enable_change_assoc_req¶
[Source]
fun box sctp_enable_change_assoc_req()
: I32 val

Returns¶

I32 val

sctp_enable_reset_assoc_req¶
[Source]


Bool val

native128¶
[Source]
fun box native128()
: Bool val

Returns¶

Bool val

debug¶
[Source]
fun box debug()
: Bool val

Returns¶


else compile_error "no SIGSTOP"
end

fun tstp(): U32 =>
ifdef bsd or osx then 18
elseif linux then 20
else compile_error "no SIGTSTP"
end

fun cont(): U32 =>
ifdef bsd or osx then 19
elseif linux then 18
else compile_error "no SIGCONT"
end

fun chld(): U32 =>
ifdef bsd or osx then 20
elseif linux then 17
else compile_error "no SIGCHLD"
end


class ForAll2[T1, T2]
let _gen1: Generator[T1] val
let _gen2: Generator[T2] val
let _helper: TestHelper

new create(
gen1': Generator[T1] val,
gen2': Generator[T2] val,
h: TestHelper)
=>
_gen1 = gen1'
_gen2 = gen2'
_helper = h

fun ref apply(prop: {(T1, T2, PropertyHelper) ?} val) ? =>
Property2UnitTest[T1, T2](
object iso is Property2[T1, T2]
fun name(): String => ""
fun gen1(): Generator[T1] => _gen1
fun gen2(): Generator[T2] => _gen2


U128 val

neg¶
[Source]
fun box neg()
: U128 val

Returns¶

U128 val

eq¶
[Source]
fun box eq(
y: U128 val)
: Bool val

Parameters¶


let _empty: Bool
var _idx: A

new create(min: A, max: A, inc: A = 1) =>
_min = min
_max = max
_inc = inc
_forward = (_min < _max) and (_inc > 0)
(let min_finite, let max_finite, let inc_finite) =
iftype A <: FloatingPoint[A] then
(_min.finite(), _max.finite(), _inc.finite())
else
(true, true, true)
end
let progress = ((_min < _max) and (_inc > 0))
or ((_min > _max) and (_inc < 0)) // false if any is NaN!
if progress and min_finite and inc_finite then
_empty = false
_infinite = not max_finite // ok to use not max_finite for max_infinite
// since progress excludes _max == nan


Bool val


min: U64 = U64.min_value(),
max: U64 = U64.max_value())
: Generator[U64]
=>
"""
Create a generator for U64 values.
"""
let that = this
Generator[U64](
object is GenObj[U64]
fun generate(rnd: Randomness): U64^ =>
rnd.u64(min, max)

fun shrink(u: U64): ValueAndShrink[U64] =>
that._int_shrink[U64](consume u, min)
end)

fun u128(
min: U128 = U128.min_value(),
max: U128 = U128.max_value())


fun exit_code(): I32 =>
"""
Retrieve the exit code of the exited process.
"""
_exit_code

fun string(): String iso^ =>
recover iso
String(10)
.>append("Exited(")
.>append(_exit_code.string())
.>append(")")
end

fun eq(other: ProcessExitStatus): Bool =>
match other
| let e: Exited =>
e._exit_code == _exit_code
else
false


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

u16_unsafe¶
[Source]
fun box u16_unsafe()
: U16 val

Returns¶

U16 val

u32_unsafe¶
[Source]


I8 val

i16¶
[Source]
fun box i16()
: I16 val

Returns¶

I16 val

i32¶
[Source]
fun box i32()
: I32 val

Returns¶


fun box sctp_mbuf_logging_enable()
: I32 val

Returns¶

I32 val

sctp_mobility_base¶
[Source]
fun box sctp_mobility_base()
: I32 val

Returns¶

I32 val

sctp_mobility_fasthandoff¶
[Source]


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

i32_unsafe¶
[Source]
fun box i32_unsafe()
: I32 val

Returns¶

I32 val

i64_unsafe¶
[Source]


Returns the next entry, or raises an error if there isn't one. If entries
are added during iteration, this may not return all entries.
"""
_i = _map.next_index(_i)?
_count = _count + 1
_map.index(_i)?


: None val

Parameters¶

len: USize val

Returns¶

None val

compact¶
[Source]
Try to remove unused space, making it available for garbage collection. The
request may be ignored. The string is returned to allow call chaining.
fun ref compact()
: None val

Returns¶


fun box eq(
that: Time val)
: Bool val

Parameters¶

that: Time val

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: Time val)
: Bool val

Parameters¶


new val create()
: HashEq[A] val^

Returns¶

HashEq[A] val^

Public Functions¶
hash¶
[Source]
Use the hash function from the type parameter.
fun box hash(
x: box->A)
: USize val

Parameters¶

x: box->A


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31


0xFFFF_FFFF_FFFF_FFFF
end

fun next_pow2(): ULong =>
let x = (this - 1).clz()
1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): ULong => this

fun bit_reverse(): ULong =>
ifdef ilp32 or llp64 then
@"llvm.bitreverse.i32"(this.u32()).ulong()
else
@"llvm.bitreverse.i64"(this.u64()).ulong()
end

fun bswap(): ULong =>
ifdef ilp32 or llp64 then
@"llvm.bswap.i32"(this.u32()).ulong()
else


972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991


fun box ipproto_gre()
: I32 val

Returns¶

I32 val

ipproto_hello¶
[Source]
fun box ipproto_hello()
: I32 val

Returns¶

I32 val

ipproto_hip¶
[Source]


fun box so_l2cap_encrypted()
: I32 val

Returns¶

I32 val

so_l2cap_flush¶
[Source]
fun box so_l2cap_flush()
: I32 val

Returns¶

I32 val

so_l2cap_iflow¶
[Source]


y: I64 val

Returns¶

I64 val

sub_unsafe¶
[Source]
fun box sub_unsafe(
y: I64 val)
: I64 val

Parameters¶

y: I64 val

Returns¶


containing the values generated by both generators.
"""
Generator[(T1, T2)](
object is GenObj[(T1, T2)]
fun generate(rnd: Randomness): GenerateResult[(T1, T2)] ? =>
(let v1: T1, let shrinks1: Iterator[T1^]) =
gen1.generate_and_shrink(rnd)?
(let v2: T2, let shrinks2: Iterator[T2^]) =
gen2.generate_and_shrink(rnd)?
((consume v1, consume v2), Iter[T1^](shrinks1).zip[T2^](shrinks2))

fun shrink(t: (T1, T2)): ValueAndShrink[(T1, T2)] =>
(let t1, let t2) = consume t
(let t11, let t1_shrunken: Iterator[T1^]) = gen1.shrink(consume t1)
(let t21, let t2_shrunken: Iterator[T2^]) = gen2.shrink(consume t2)

let shrunken = Iter[T1^](t1_shrunken).zip[T2^](t2_shrunken)
((consume t11, consume t21), shrunken)
end)


Real[A] val^

max_value¶
[Source]
new val max_value()
: Real[A] val^

Returns¶

Real[A] val^

Public Functions¶
add_unsafe¶
[Source]
Unsafe operation.
If the operation overflows, the result is undefined.
fun box add_unsafe(
y: A)


produced. Uniqueness is determined by the HashFunction H.
Example¶
Iter[USize]([as USize: 1; 2; 1; 1; 3; 4; 1].values())
.unique()

1 2 3 4
fun ref unique[optional H: HashFunction[A] val]()
: Iter[A!] ref^

Returns¶

Iter[A!] ref^

zip[B: B]¶
[Source]
Zip two iterators together so that each call to next() results in
a tuple with the next value of the first iterator and the next value
of the second iterator. The number of items returned is the minimum of
the number of items returned by the two iterators.


I16 val

i32_unsafe¶
[Source]
fun box i32_unsafe()
: I32 val

Returns¶

I32 val

i64_unsafe¶
[Source]
fun box i64_unsafe()
: I64 val

Returns¶


732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751


FileStat¶
[Source]
primitive val FileStat

Constructors¶
create¶
[Source]
new val create()
: FileStat val^

Returns¶

FileStat val^


fun box op_and(
y: I128 val)
: I128 val

Parameters¶

y: I128 val

Returns¶

I128 val

op_or¶
[Source]
fun box op_or(
y: I128 val)
: I128 val

Parameters¶


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451


712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731


FileError¶
[Source]
primitive val FileError

Constructors¶
create¶
[Source]
new val create()
: FileError val^

Returns¶

FileError val^


1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291