# Usage

Creating an Array of String:
```pony
let array: Array[String] = ["dog"; "cat"; "wombat"]
// array.size() == 3
// array.space() >= 3
```

Creating an empty Array of String, which may hold at least 10 elements before
requesting more space:
```pony
let array = Array[String](10)
// array.size() == 0
// array.space() >= 10
```

Accessing elements can be done via the `apply(i: USize): this->A ?` method.
The provided index might be out of bounds so `apply` is partial and has to be
called within a try-catch block or inside another partial method:


Reverse[optional A: (Real[A] val & (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))]¶
[Source]
Produces a decreasing range [max, min] with step dec, for any Number type.
(i.e. the reverse of Range)
Example program:
use "collections"
actor Main
new create(env: Env) =>
for e in Reverse(10, 2, 2) do
env.out.print(e.string())
end

Which outputs:


# What guarantees does Pony's type system give me?

The Pony type system offers a lot of guarantees, even more than other statically typed languages.

* If your program compiles, it won't crash.
* There will never be an unhandled exception.
* There's no such thing as `null`, so your program will never try to dereference `null`.
* There will never be a data race.
* Your program will never deadlock.
* Your code will always be capabilities-secure.
* All message passing is
[causal](https://courses.cs.vt.edu/~cs5204/fall00/causal.html). (Not **casual**!)

Some of those will make sense right now. Some of them may not mean much to you yet (like capabilities-security and causal messaging), but we'll get to those concepts later on.

__If I use Pony's FFI to call code written in another language, does Pony make the same guarantees for the code I call?__ Sadly, no. Pony's type system can only guarantee code written in Pony. Code written in other languages get only the guarantees provided by that language.

Pony requires FFI parameters to be explicitly declared as Pony types in advance. The type system provides a guarantee at compile-time that no code-paths exist that violate the definitions you provided on the Pony side of your FFI call.

This guarantee cannot be inclusive of foreign code as the compiler has no way to verify that it won't violate Pony's type system guarantees at runtime.


52
53
54
55
56
57
58
59
60primitive ASCIINUL
fun apply(): String => "\x00"

primitive ASCIIDigits
fun apply(): String => "0123456789"

primitive ASCIIWhiteSpace
fun apply(): String => " \t\n\r\x0b\x0c"

primitive ASCIIPunctuation
fun apply(): String => "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"


for name in ["Bob"; "Fred"; "Sarah"].values() do
name
end
match x
| let s: String => env.out.print("x is " + s)
| None => env.out.print("x is None")
end
```

This will give __x__ the value "Sarah" as it is the last name in our list. If our loop has 0 iterations, then the value of its `else` block will be the value of __x__. Or if there is no `else` block, the value will be `None`.

```pony
actor Main
new create(env: Env) =>
var x: (String | None) =
for name in Array[String].values() do
name
end
match x
| let s: String => env.out.print("x is " + s)


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


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


752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771


fun box sub_unsafe(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

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

Parameters¶


### Example

```pony
Iter[USize]([as USize: 1; 2; 1; 1; 3; 4; 1].values())
.unique()
```
`1 2 3 4`
"""
Iter[A!](
object
let _set: HashSet[A!, H] = HashSet[A!, H]()

fun ref has_next(): Bool =>
_iter.has_next()

fun ref next(): A! ? =>
let v = _iter.next()?
if _set.contains(v) then
next()?
else


Parameters¶

min: ULong val = call
max: ULong val = call

Returns¶

Generator[ULong val] box

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

Parameters¶


y: USize val

Returns¶

(USize val , Bool val)

mulc¶
[Source]
fun box mulc(
y: USize val)
: (USize val , Bool val)

Parameters¶

y: USize val

Returns¶


: File ref^

Parameters¶

from: FilePath val

Returns¶

File ref^

open¶
[Source]
Open for read only.
Set _errno according to result.
new ref open(
from: FilePath val)
: File ref^

Parameters¶


Create a generator for `Set` filled with values
of the given generator `gen`.
The returned sets will have a size up to `max`,
but tend to have fewer than `max`
depending on the source generator `gen`.

E.g. if the given generator is for `U8` values and `max` is set to 1024,
the set will only ever be of size 256 max.

Also for efficiency purposes and to not loop forever,
this generator will only try to add at most `max` values to the set.
If there are duplicates, the set won't grow.
"""
Generator[Set[T]](
object is GenObj[Set[T]]
let _gen: GenObj[T] = gen
fun generate(rnd: Randomness): GenerateResult[Set[T]] =>
let size = rnd.usize(0, max)
let result: Set[T] =
Set[T].create(size).>union(


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


fun box ipv6_priority_11()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_priority_13¶
[Source]


fun box sctp_pcb_flags_udptype()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_wakeinput¶
[Source]


signed.pony

1
2
3
4
5
6
7
8
9
10
11


int_properties.pony

1
2
3
4
5
6
7
8
9
10
11


# An example

Consider SQLite, mentioned earlier. When the client code calls `sqlite3_exec`, an SQL query is executed against a database, and the callback function is called for each row returned by the SQL statement. Here's the signature for `sqlite3_exec`:

```c
typedef int (*sqlite3_callback)(void*,int,char**, char**);

...

SQLITE_API int SQLITE_STDCALL sqlite3_exec(
sqlite3 *db,                /* The database on which the SQL executes */
const char *zSql,           /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
void *pArg,                 /* First argument to xCallback() */
char **pzErrMsg             /* Write error messages here */
)
{
...
xCallback(pArg, nCol, azVals, azCols)
...


Allows stateful modification to the stream of elements from an iterator,
similar to `filter_map`.
"""
Iter[B](
object is Iterator[B]
var _next: (B | _None) = _None

fun ref _find_next() =>
try
match _next
| _None =>
if _iter.has_next() then
match f(_iter.next()?)?
| let b: B => _next = consume b
| None => _find_next()
end
end
end
end


fun box ip_bindany()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_bind_address_no_port¶
[Source]


u8¶
fun ref u8()
: U8 val

Returns¶

U8 val

u16¶
fun ref u16()
: U16 val

Returns¶

U16 val

u32¶


be _read_again() =>
"""
Resume reading.
"""
_pending_reads()

fun ref write_final(data: ByteSeq) =>
"""
Write as much as possible to the socket. Set `_writeable` to `false` if not
everything was written. On an error, close the connection. This is for data
that has already been transformed by the notifier. Data will be silently
discarded if the connection has not yet been established though.
"""
// don't sent 0 byte payloads; windows doesn't like it (and it's wasteful)
if data.size() == 0 then
return
end

if _connected and not _closed then


"""
if i < _size then
_ptr._update(i, consume value)
else
error
end

fun ref insert(i: USize, value: A) ? =>
"""
Insert an element into the array. Elements after this are moved up by one
index, extending the array.

When inserting right beyond the last element, at index `this.size()`,
the element will be appended, similar to `push()`,
an insert at index `0` prepends the value to the array.
An insert into an index beyond `this.size()` raises an error.

```pony
let array = Array[U8](4)              // []
array.insert(0, 0xDE)?                // prepend: [0xDE]


end

fun trap(): U32 =>
ifdef linux or bsd or osx then 5
else compile_error "no SIGTRAP"
end

fun abrt(): U32 => 6

fun emt(): U32 =>
ifdef bsd or osx then 7
else compile_error "no SIGEMT"
end

fun fpe(): U32 =>
ifdef linux or bsd or osx then 8
else compile_error "no SIGFPE"
end

fun kill(): U32 => 9


align.pony

1
2
3
4
5
6
7
8primitive AlignLeft
primitive AlignRight
primitive AlignCenter


notify: (InputNotify iso | None val),
chunk_size: USize val = 32)

Parameters¶

notify: (InputNotify iso | None val)
chunk_size: USize val = 32

dispose¶
[Source]
Clear the notifier in order to shut down input.
be dispose()


Cap val^

Public Functions¶
enter¶
[Source]
This places the current process into capability mode, a mode of execution
in which processes may only issue system calls operating on file
descriptors or reading limited global system state. Access to global name
spaces, such as file system or IPC name spaces, is prevented.
fun box enter()
: Bool val

Returns¶

Bool val

read¶
[Source]


fun box so_debug()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_detach_filter¶
[Source]


None val

u128_le¶
[Source]
Write a U128 to the buffer in little-endian byte order.
fun ref u128_le(
data: U128 val)
: None val

Parameters¶

data: U128 val

Returns¶

None val


fun box ctz_unsafe()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

bytewidth¶
[Source]


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

Parameters¶

y: U8 val

Returns¶

U8 val

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

Parameters¶


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

Parameters¶

y: I8 val

Returns¶

I8 val

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

Parameters¶


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


use @pony_os_errno[I32]()

use "collections"

primitive FileOK
primitive FileError
primitive FileEOF
primitive FileBadFileNumber
primitive FileExists
primitive FilePermissionDenied

primitive _EBADF
fun apply(): I32 => 9

primitive _EEXIST
fun apply(): I32 => 17

primitive _EACCES
fun apply(): I32 => 13


fun box tcpf_ca_cwr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpf_ca_loss¶
[Source]


let size: USize = // ...
// ...
@memcpy(out, addressof ptr, size.bitwidth() / 8)
@memcpy(outlen, addressof size, 1)
```

When dealing with `void*` return types from C, it is good practice to try to narrow the type down to the most specific Pony type that you expect to receive. In the example above, we chose `Pointer[U8]` as the return type, since we can use such a pointer to construct Pony Arrays and Strings.

To pass pointers to values to C the `addressof` operator can be used (previously `&`), just like taking an address in C. This is done in the standard library to pass the address of a `U32` to an FFI function that takes a `int*` as an out parameter:

```pony
use @frexp[F64](value: F64, exponent: Pointer[U32])
// ...
var exponent: U32 = 0
var mantissa = @frexp(this, addressof exponent)
```


fun box ipproto_beetph()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_blt¶
[Source]


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


// make a reversed version
let str_reversed = str.reverse()

// add " world" to the end of our original string
let str_new = str.add(" world")

// count occurrences of letter "l"
let count = str_new.count("l")

// find first occurrence of letter "w"
let first_w = str_new.find("w") ?
// find first occurrence of letter "d"
let first_d = str_new.find("d") ?

// get substring capturing "world"
let substr = str_new.substring(first_w, first_d+1)
// clone substring
let substr_clone = substr.clone()

// print our substr


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


if _registry(key)? is value then
_registry.remove(key)?
end
end

fun tag apply[A: Any tag = Any tag](key: String): Promise[A] =>
"""
Lookup by name. Returns a promise that will be fulfilled with the mapped
value if it exists and is a subtype of A. Otherwise, the promise will be
rejected.
"""
let promise = Promise[A]
_fetch[A](key, promise)
promise

be _fetch[A: Any tag](key: String, promise: Promise[A]) =>
"""
Fulfills or rejects the promise.
"""
try


NoProxy¶
[Source]
Default implementation of a proxy that does not alter the supplied TCPConnectionNotify.
actor MyClient
new create(host: String, service: String, proxy: Proxy = NoProxy) =>
let conn: TCPConnection = TCPConnection.create(
TCPConnectAuth(env.root),
proxy.apply(MyConnectionNotify.create()),
"localhost",
"80")

class val NoProxy is
Proxy ref


(3, 0xEF, 0xBF, 0xBD, 0)
end


Parameters¶

n: USize val

Returns¶

Iter[A] ref^

skip_while¶
[Source]
Skip values of the iterator while the predicate f returns true.
Example¶
Iter[I64]([1; 2; 3; 4; 5; 6].values())
.skip_while({(x) => x < 4 })

4 5 6
fun ref skip_while(
f: {(A!): Bool ?}[A] box)


y: I128 val

Returns¶

I128 val

neg_unsafe¶
[Source]
fun box neg_unsafe()
: I128 val

Returns¶

I128 val

op_and¶
[Source]


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651


fun box sctp_i_want_mapped_v4_addr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_listen¶
[Source]


fun box so_sco_mtu()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_security_encryption_network¶
[Source]


flags = flags or @ponyint_o_creat() or @ponyint_o_trunc()
end
end

_fd = ifdef windows then
@_open(path.path.cstring(), flags, mode.i32())
else
@open(path.path.cstring(), flags, mode)
end

if _fd == -1 then
_errno = _get_error()
else
try
_FileDes.set_rights(_fd, path, writeable)?
else
_errno = FileError
end
end
end


Bool val


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


1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111


992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011


_alloc = data.space()
_ptr = (consume data).cpointer()._unsafe()
if _alloc > _size then
_set(_size, 0)
end

new from_cpointer(str: Pointer[U8], len: USize, alloc: USize = 0) =>
"""
Return a string from binary pointer data without making a
copy. This must be done only with C-FFI functions that return
pony_alloc'd character arrays. 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)
else
_size = len


loc: SourceLoc = __loc)
: Bool
=>
"""
Assert that the 2 given expressions are not equal.
"""
if not_expect == actual then
_fail(_fmt_msg(loc, "Assert ne failed. " + msg
+ " Expected (" + not_expect.string() + ") != (" + actual.string()
+ ")"))
return false
end

_runner.log(
_fmt_msg(loc, "Assert ne passed. " + msg
+ " Got (" + not_expect.string() + ") != (" + actual.string() + ")"),
true)
true

fun assert_array_eq[A: (Equatable[A] #read & Stringable #read)](


fun box ipproto_argus()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_beetph¶
[Source]


__Why can't I just say "else if" like I do in C? Why the extra keyword?__ The relationship between `if` and `else` in C, and other similar languages, is ambiguous. For example:

```c
// C code
if(a)
if(b)
printf("a and b\n");
else
printf("not a\n");
```

Here it is not obvious whether the `else` is an alternative to the first or the second `if`. In fact here the `else` relates to the `if(b)` so our example contains a bug. Pony avoids this type of bug by handling `if` and `else` differently and the need for `elseif` comes out of that.


Returns false and closes the file if not all the bytes were written.
"""
queue(data)

_pending_writes()

fun ref writev(data: ByteSeqIter box): Bool =>
"""
Write an iterable collection of ByteSeqs.
"""
for bytes in data.values() do
queue(bytes)
end

_pending_writes()

fun ref queue(data: ByteSeq box) =>
"""
Queue data to be written
NOTE: Queue'd data will always be written before normal print/write


WaitpidError¶
[Source]
primitive val WaitpidError

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

Returns¶

WaitpidError val^


fun box rds_cmsg_atomic_cswp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_cmsg_cong_update¶
[Source]


ISize val

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

Parameters¶

y: ISize val

Returns¶

(ISize val , Bool val)

subc¶


fun box so_rcvtimeo_old()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_sndtimeo_old¶
[Source]


fun box ipport_ephemerallast()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipport_hilastauto¶
[Source]


_start_next_read()

new ip6(
auth: UDPAuth,
notify: UDPNotify iso,
host: String = "",
service: String = "0",
size: USize = 1024)
=>
"""
Listens for IPv6 datagrams.
"""
_notify = consume notify
_event =
@pony_os_listen_udp6(this, host.cstring(), service.cstring())
_fd = @pony_asio_event_fd(_event)
@pony_os_sockname(_fd, _ip)
_packet_size = size
_read_buf = recover Array[U8] .> undefined(size) end
_notify_listening()


Bool val

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

Parameters¶

y: U8 val

Returns¶

Bool val

ge¶
[Source]


fun box ip_old_fw_add()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_old_fw_flush¶
[Source]


be fail_action(name: String, round: _Round, ph: PropertyHelper) =>
if round != this._current_round then
_logger.log("unexpected fail action \"" + name + "\" msg for " + round.string() +
". Currently at " + this._current_round.string(), true)
return
end
_logger.log("Action failed: " + name)
_finish_action(name, false, round, ph)

fun ref _finish_action(name: String, success: Bool, round: _Round, ph: PropertyHelper) =>
try
_expected_actions.extract(name)?

// call back into the helper to invoke the current run_notify
// that we don't have access to otherwise
if not success then
ph.complete(false)
elseif _expected_actions.size() == 0 then
ph.complete(true)


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

Parameters¶

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

Returns¶

Nil[A] val

contains[optional T: (A & HasEq[A!] #read)]¶
[Source]
fun val contains[optional T: (A & HasEq[A!] #read)](
a: val->T)
: Bool val

Parameters¶


USize val

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

Parameters¶

y: USize val

Returns¶

USize val

op_or¶
[Source]


Bool val

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

Parameters¶

that: FormatHexBare val

Returns¶

Bool val


fun neg_unsafe(): A =>
"""
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.
"""
-~this

fun eq_unsafe(y: box->A): Bool =>
"""
Unsafe operation.
If any input of the operation is +/- infinity or NaN, the result is
undefined.
The operation isn't required to fully comply to IEEE 754 semantics.
"""
this ==~ y

fun ne_unsafe(y: box->A): Bool =>
"""


disposable: DisposableActor tag

Returns¶

None val


Serialise package¶
This package provides support for serialising and deserialising arbitrary data
structures.
The API is designed to require capability tokens, as otherwise serialising
would leak the bit patterns of all private information in a type if the
resulting Array[U8] could be examined.
Deserialisation is fundamentally unsafe currently: there isn't yet a
verification pass to check that the resulting object graph maintains a
well-formed heap or that individual objects maintain any expected local
invariants. However, if only "trusted" data (i.e. data produced by Pony
serialisation from the same binary) is deserialised, it will always maintain a
well-formed heap and all object invariants.
Note that serialised data is not usable between different Pony binaries. This is


dispose¶
[Source]
Dispose of this set of timing wheels.
be dispose()


fun box acosh()
: A

Returns¶

A

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

Returns¶

A

atanh¶
[Source]


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


fun blue(): String =>
"""
Blue text.
"""
"\x1B[34m"

fun magenta(): String =>
"""
Magenta text.
"""
"\x1B[35m"

fun cyan(): String =>
"""
Cyan text.
"""
"\x1B[36m"

fun grey(): String =>


new val _create(run_async: _RunAsync, f: {(U64)} val) =>
_run_async = run_async
_f = f

fun complete() =>
let e = Time.nanos()
_f(e)

fun fail() =>
_run_async._fail()


if caps(FileTime) then set(Cap.futimes()) end
if caps(FileTruncate) then set(Cap.ftruncate()) end
if caps(FileWrite) then set(Cap.write()) end
if caps(FileExec) then set(Cap.fexecve()) end

new descriptor(fd: I32) =>
"""
Initialises with the rights on the given file descriptor.
"""
ifdef freebsd or "capsicum" then
@__cap_rights_get(_version(), fd, addressof _r0)
end

fun ref set(cap: U64) =>
ifdef freebsd or "capsicum" then
@__cap_rights_set(addressof _r0, cap, U64(0))
end

fun ref unset(cap: U64) =>
ifdef freebsd or "capsicum" then


fun box netlink_connector()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

netlink_dnrtmsg¶
[Source]


A method verifying that a certain property holds for all given
arg1,arg2, and arg3
with the help of PropertyHelper h.
fun ref property3(
arg1: T1,
arg2: T2,
arg3: T3,
h: PropertyHelper val)
: None val ?

Parameters¶

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

Returns¶

None val ?


# Delegating and restricting authority

Any interesting program will need to interact with the outside world, like accessing the network or the file system, or by creating and communicating with other programs. We call __ambient authority__ all those rights implicitly granted to the program to make these things possible, and because Pony makes this concept *explicit*, we need to take the time to talk about what it means and how it works. In other languages like for example C, you can always attempt to do an operation like I/O, and it will usually succeed save some runtime checks (your disk being full might make an operation fail, for example). But in Pony, any piece of code interacting with the outside world needs the authority to do so.

The operating system essentially knows nothing about the structure of any program it runs, in particular it is ignorant of any Pony specific concepts. In order to impose that some code is authorized for an operation like writing to disk, Pony requires a special argument to be passed, a capability bearing the authority required for the task at hand. The type system guarantees that inadequate capabilities for a task fail at compile time.

Recall the definition of capability from the [Object Capabilities](/object-capabilities/object-capabilities.md) section:

> A capability is an unforgeable token that (a) designates an object and (b) gives the program the authority to perform a specific set of actions on that object.

In Pony, the `Main` actor is created with an `Env` object, which holds the unforgeable `AmbientAuth` token in its root field. This value is the capability that represents the ambient authority given to us by the system.

Here is a program that connects to example.com via TCP on port 80 and quits:

```pony
use "net"

class MyTCPConnectionNotify is TCPConnectionNotify
let _out: OutStream


fun box ctz()
: A

Returns¶

A

clz_unsafe¶
[Source]
Count leading zeroes.
Unsafe operation.
If this is 0, the result is undefined.
fun box clz_unsafe()
: A

Returns¶

A


fun box mulc(
y: I32 val)
: (I32 val , Bool val)

Parameters¶

y: I32 val

Returns¶

(I32 val , Bool val)

divc¶
[Source]
fun box divc(
y: I32 val)
: (I32 val , Bool val)

Parameters¶


PonyBench¶
[Source]
actor tag PonyBench

Constructors¶
create¶
[Source]
new tag create(
env: Env val,
list: BenchmarkList tag)
: PonyBench tag^

Parameters¶


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


vec

fun val reverse(): Vec[A] =>
"""
Return a vector with the elements in reverse order.
"""
var vec = Vec[A]
for i in mut.Reverse(_size - 1, 0) do
try vec = vec.push(this(i)?) end
end
vec

fun val keys(): VecKeys[A]^ =>
"""
Return an iterator over the indices in the vector.
"""
VecKeys[A](this)

fun val values(): VecValues[A]^ =>
"""


string¶
[Source]
Creates an Option with a String typed value that can be used like
--file=dir/filename or -F=dir/filename or -Fdir/filename
to yield an option value like
cmd.option("file").string() == "dir/filename".
new val string(
name': String val,
descr': String val = "",
short': (U8 val | None val) = reference,
default': (String val | None val) = reference)
: OptionSpec val^

Parameters¶

name': String val
descr': String val = ""
short': (U8 val | None val) = reference


"""
Underlined text. Does nothing on Windows.
"""
if state then "\x1B[4m" else "\x1B[24m" end

fun blink(state: Bool = true): String =>
"""
Blinking text. Does nothing on Windows.
"""
if state then "\x1B[5m" else "\x1B[25m" end

fun reverse(state: Bool = true): String =>
"""
Swap foreground and background colour.
"""
if state then "\x1B[7m" else "\x1B[27m" end

fun black(): String =>
"""
Black text.


fun box rds_info_connections()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_info_connection_flag_connecting¶
[Source]


fun box udp_no_check6_tx()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_rcvtimeo_old¶
[Source]


Parameters¶

samples': USize val = 20
max_iterations': U64 val = 1000000000
max_sample_time': U64 val = 100000000

Returns¶

BenchConfig val^

Public fields¶
let samples: USize val¶
[Source]
Total number of samples to be measured. (Default: 20)

let max_iterations: U64 val¶
[Source]
Maximum number of iterations to execute per sample. (Default: 1_000_000_000)


let last = _size.min(to)
let offset = last.min(from)
let size' = last - offset

// use the new size' for alloc if we're not including the last used byte
// from the original data and only include the extra allocated bytes if
// we're including the last byte.
_alloc = if last == _size then _alloc - offset else size' end

_size = size'

// if _alloc == 0 then we've trimmed all the memory originally allocated.
// if we do _ptr._offset, we will spill into memory not allocated/owned
// by this array and could potentially cause a segfault if we cross
// a pagemap boundary into a pagemap address that hasn't been allocated
// yet when `reserve` is called next.
if _alloc == 0 then
_ptr = Pointer[A]
else
_ptr = _ptr._offset(offset)


Parameters¶

that: F64 val

Returns¶

(Less val | Equal val | Greater val)


fun box string()
: String iso^

Returns¶

String iso^

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

Parameters¶

y: U128 val

Returns¶


fun box sctp_cause_nat_missing_state()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cause_no_user_data¶
[Source]


ascii_range.pony

1
2
3
4
5
6
7
8
9
10
11


fun box tcp_maxwin()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_max_winshift¶
[Source]


# Operator aliasing

Most infix operators in Pony are actually aliases for functions. The left operand is the receiver the function is called on and the right operand is passed as an argument. For example, the following expressions are equivalent:

```pony
x + y
x.add(y)
```

This means that `+` is not a special symbol that can only be applied to magic types. Any type can provide its own `add` function and the programmer can then use `+` with that type if they want to.

When defining your own `add` function there is no restriction on the types of the parameter or the return type. The right side of the `+` will have to match the parameter type and the whole `+` expression will have the type that `add` returns.

Here's a full example for defining a type which allows the use of `+`. This is all you need:

```pony
// Define a suitable type
class Pair
var _x: U32 = 0
var _y: U32 = 0


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

Parameters¶

that: EraseLeft val

Returns¶

Bool val


To understand this error message, you have to have some background. The field `color` is mutable since it is declared with `var`, but the method `dye` does not have an explicit receiver reference capability. The default receiver reference capability is `box`, which allows `dye` to be called on any mutable or immutable `Wombat`; the `box` reference capability says that the method may read from but not write to the receiver. As a result, it is illegal to attempt to modify the receiver in the method.

To fix the error, you would need to give the `dye` method a mutable reference capability, such as `ref`: `fun ref dye(new_color: String) => ...`.


A

div¶
[Source]
Integer division, rounded towards zero.
fun box div(
y: A)
: A

Parameters¶

y: A

Returns¶

A

divrem¶


612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631


to yield an option value like
`cmd.option("ratio").f64() == F64(1.039)`.
"""
_name = name'
_descr = descr'
_short = short'
(_typ, _default, _required) = _init(_F64Type, default')

new val string_seq(
name': String,
descr': String = "",
short': (U8 | None) = None)
=>
"""
Creates an Option with a ReadSeq[String] typed value that can be used like
`--files=file1 --files=files2 --files=files2`
to yield a sequence of three strings equivalent to
`cmd.option("ratio").string_seq() (equiv) ["file1"; "file2"; "file3"]`.
"""
_name = name'


end

fun mulc(y: USize): (USize, Bool) =>
ifdef ilp32 then
(let r, let o) =
@"llvm.umul.with.overflow.i32"(this.u32(), y.u32())
(r.usize(), o)
else
(let r, let o) =
@"llvm.umul.with.overflow.i64"(this.u64(), y.u64())
(r.usize(), o)
end

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

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

fun add_partial(y: USize): USize ? =>


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


52
53
54
55
56
57
58
59use @ponyint_gmtime[None](date: PosixDate, sec: I64, nsec: I64)
use @ponyint_timegm[I64](date: PosixDate tag)
use @ponyint_formattime[Pointer[U8]](date: PosixDate tag, fmt: Pointer[U8] tag) ?

class PosixDate
"""
Represents a proleptic Gregorian date and time, without specifying a
time zone. The day of month, month, day of week, and day of year are all
indexed from 1, i.e. January is 1, Monday is 1.
"""
var nsec: I32 = 0
var sec: I32 = 0
var min: I32 = 0


fun box tcpopt_pad()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpopt_sack_hdr¶
[Source]


ifdef ilp32 or llp64 then
@"llvm.cttz.i32"(this.u32(), false).ulong()
else
@"llvm.cttz.i64"(this.u64(), true).ulong()
end

fun bitwidth(): ULong => ifdef ilp32 or llp64 then 32 else 64 end

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

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

fun hash(): USize =>
ifdef ilp32 or llp64 then
u32().hash()
else
u64().hash()
end


chmod¶
[Source]
Set the FileMode for this directory.
fun box chmod(
mode: FileMode box)
: Bool val

Parameters¶

mode: FileMode box

Returns¶

Bool val

chown¶
[Source]
Set the owner and group for this directory. Does nothing on Windows.
fun box chown(


var owner_read: Bool val¶
[Source]
true if the owning user can read the file.

var owner_write: Bool val¶
[Source]
true if the owning user can write to the file.

var owner_exec: Bool val¶
[Source]
true if the owning user can execute the file.

var group_read: Bool val¶
[Source]
true if members of the owning group can read the file.

var group_write: Bool val¶
[Source]
true if members of the owning group can write to the file.


y: I16 val

Returns¶

I16 val ?

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

Parameters¶

y: I16 val

Returns¶


```pony
let key = recover val line.substring(0, i).>strip() end
```

That's from `net/http/_PayloadBuilder`. We get a substring of `line`, which is a `String iso^`, then we call strip on it, which returns itself. But since strip is a `ref` function, it returns itself as a `String ref^` - so we use a `recover val` to end up with a `String val`.


gt_unsafe¶
fun box gt_unsafe(
y: F32 val)
: Bool val

Parameters¶

y: F32 val

Returns¶

Bool val

string¶
fun box string()
: String iso^


Returns the bit encoding of the set flags.
"""
_value

fun apply(flag: A): Bool =>
"""
Returns true if the flag is set.
"""
(_value and flag.value()) > 0

fun ref all() =>
"""
Sets all bits, including undefined flags.
"""
_value = -1

fun ref clear() =>
"""
Unsets all flags.
"""


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


new val create()
: FormatHexSmallBare val^

Returns¶

FormatHexSmallBare val^

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

Parameters¶

that: FormatHexSmallBare val

Returns¶


fun box f64_unsafe()
: F64 val

Returns¶

F64 val

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

Parameters¶

that: ULong val

Returns¶


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


ULong val

clz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.
fun box clz_unsafe()
: ULong val

Returns¶

ULong val

ctz_unsafe¶
[Source]
Unsafe operation.
If this is 0, the result is undefined.


posix_date.pony

1
2
3
4
5
6
7
8
9
10
11


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


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

Returns¶

String val

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

Parameters¶


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


fun box usize_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64_unsafe¶
[Source]


that: FileChmod val

Returns¶

Bool val

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

Parameters¶

that: FileChmod val

Returns¶


fun box rds_cmsg_masked_atomic_fadd()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_cmsg_rdma_dest¶
[Source]


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651


fun box sctp_get_local_addresses()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_get_nonce_values¶
[Source]


// file itself needs to be an executable
if not filepath.caps(FileExec) then
_notifier.failed(this, ProcessError(CapError, filepath.path
+ " is not an executable or we do not have execute capability."))
return
end

let ok = try
FileInfo(filepath)?.file
else
false
end
if not ok then
// unable to stat the file path given so it may not exist
// or may be a directory.
_notifier.failed(this, ProcessError(ExecveError, filepath.path
+ " does not exist or is a directory."))
return
end


MaxHeap[A: Comparable[A] #read]¶
[Source]
type MaxHeap[A: Comparable[A] #read] is
BinaryHeap[A, MaxHeapPriority[A] val] ref

Type Alias For¶

BinaryHeap[A, MaxHeapPriority[A] val] ref


fun tag strings_to_sizes(sa: Array[String] val): Array[USize] val =>
recover
let len = Array[USize]
for s in sa.values() do
len.push(s.size())
end
len
end
fun tag sizes_to_avg(sza: Array[USize] val): USize =>
var acc = USize(0)
for sz in sza.values() do
acc = acc + sz
end
acc / sza.size()
fun tag output(env: Env, sz: USize): None =>
env.out.print(sz.string())

actor Main
new create(env: Env) =>
let promise = Promise[String]


# Property Based Testing

In _traditional_ unit testing, the developer specifies one or more input
examples manually for the class or system under test and asserts on certain
output conditions. The difficulty here is to find enough examples to cover
all branches and cases of the class or system under test.

In property based testing, the developer defines a property, a kind of predicate
for the class or system under test that should hold for all kinds or just a
subset of possible input values. The property based testing engine then
generates a big number of random input values and checks if the property holds
for all of them. The developer only needs to specify the possible set of input
values using a Generator.

This testing technique is great for finding edge cases that would easily go
unnoticed with manually constructed test samples. In general it can lead to much
higher coverage than traditional unit testing, with much less code to write.


Iter[String^].chain([
shorten_iter
min_iter
].values())
(consume s, shrink_iter)
end)

fun ascii(
min: USize = 0,
max: USize = 100,
range: ASCIIRange = ASCIIAll)
: Generator[String]
=>
"""
Create a generator for strings withing the given `range`,
with a minimum length of `min` (default: 0)
and a maximum length of `max` (default: 100).
"""
let range_bytes = range.apply()
let fallback = U8(0)


exponent: I32 val)
: F32 val

Parameters¶

x: F32 val
exponent: I32 val

Returns¶

F32 val

frexp¶
[Source]
fun box frexp()
: (F32 val , U32 val)

Returns¶


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


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

Parameters¶

y: I16 val

Returns¶

I16 val

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

Returns¶


"""
// True if exponent is all 1s and mantissa is 0
((bits() and 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000) and  // exp
((bits() and 0x000F_FFFF_FFFF_FFFF) == 0)  // mantissa

fun nan(): Bool =>
"""
Check whether this number is NaN.
"""
// True if exponent is all 1s and mantissa is non-0
((bits() and 0x7FF0_0000_0000_0000) == 0x7FF0_0000_0000_0000) and  // exp
((bits() and 0x000F_FFFF_FFFF_FFFF) != 0)  // mantissa

fun ldexp(x: F64, exponent: I32): F64 =>
@ldexp(x, exponent)

fun frexp(): (F64, U32) =>
var exponent: U32 = 0
var mantissa = @frexp(this, addressof exponent)
(mantissa, exponent)


# What goes in a class?

A class is composed of:

1. Fields.
2. Constructors.
3. Functions.


fun box mod_unsafe(
y: U16 val)
: U16 val

Parameters¶

y: U16 val

Returns¶

U16 val

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

Parameters¶


Parameters¶

auth: AmbientAuth val

Returns¶

SerialiseAuth val^

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

Parameters¶

that: SerialiseAuth val


[Source]
Called if the timer is cancelled. This is also called if the notifier
returns false from its apply method.
fun ref cancel(
timer: Timer ref)
: None val

Parameters¶

timer: Timer ref

Returns¶

None val


fun box sctp_stream_reset_incoming()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_str_logging_enable¶
[Source]


fun box ip_origdstaddr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_pktinfo¶
[Source]


fun peek_u128_le(offset: USize = 0): U128 ? =>
"""
Peek at a little-endian U128.
"""
peek_u64_le(offset)?.u128() or (peek_u64_le(offset + 8)?.u128() << 64)

fun peek_i128_be(offset: USize = 0): I128 ? =>
"""
Peek at a big-endian I129.
"""
peek_u128_be(offset)?.i128()

fun peek_i128_le(offset: USize = 0): I128 ? =>
"""
Peek at a little-endian I128.
"""
peek_u128_le(offset)?.i128()

fun peek_f32_be(offset: USize = 0): F32 ? =>
"""


debug.pony

1
2
3
4
5
6
7
8
9
10
11


test_list.pony

1
2
3
4
5
6
7
8
9
10
11


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


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


unthrottled¶
[Source]
Called when the connection stops experiencing TCP backpressure. Upon
receiving this notification, you should feel free to start making calls to
write and writev again.
fun ref unthrottled(
conn: TCPConnection ref)
: None val

Parameters¶

conn: TCPConnection ref

Returns¶

None val


fun box ipx_extended_address()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipx_frame_8022¶
[Source]


try
let delim_start = find(delim where offset = current)?
result.push(substring(current, delim_start))
current = delim_start + delim_size
else break end
end
result.push(substring(current))
consume result

fun split(delim: String = " \t\v\f\r\n", n: USize = 0): Array[String] iso^ =>
"""
Split the string into an array of strings with any character in the
delimiter string. By default, the string is split with whitespace
characters. If `n > 0`, then the split count is limited to n.

Example:

```pony
let original: String = "name,job;department"
let delimiter: String = ".,;"


Returns¶

String val

bright_blue¶
[Source]
Bright blue text.
fun box bright_blue()
: String val

Returns¶

String val

bright_magenta¶
[Source]
Bright magenta text.


872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891


y: U128 val

Returns¶

Bool val

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

Parameters¶

y: U128 val

Returns¶


U8 val

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

Parameters¶

y: U8 val

Returns¶

U8 val

divrem¶
[Source]


_notify = consume notify
_event =
@pony_os_listen_tcp(this, host.cstring(), service.cstring())
_read_buffer_size = read_buffer_size
_yield_after_reading = yield_after_reading
_yield_after_writing = yield_after_writing
_fd = @pony_asio_event_fd(_event)
_notify_listening()

new ip4(
auth: TCPListenAuth,
notify: TCPListenNotify iso,
host: String = "",
service: String = "0",
limit: USize = 0,
read_buffer_size: USize = 16384,
yield_after_reading: USize = 16384,
yield_after_writing: USize = 16384)
=>
"""


Parameters¶

that: Flags[A, B] box

Returns¶

None val

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

Parameters¶

flag: A


I128 val

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

Returns¶

ILong val

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

Returns¶


_size = 0

fun ref push_u8[B: (A & Real[B] val & U8) = A](value: U8) =>
"""
Add a U8 to the end of the array. This is only allowed for an array of U8s.
"""
let u8_bytes = U8(0).bytewidth()
reserve(_size + u8_bytes)
_ptr._offset(_size)._convert[U8]()._update(0, value)
_size = _size + u8_bytes

fun ref push_u16[B: (A & Real[B] val & U8) = A](value: U16) =>
"""
Add a U16 to the end of the array. This is only allowed for an array of U8s.
"""
let u16_bytes = U16(0).bytewidth()
reserve(_size + u16_bytes)
_ptr._offset(_size)._convert[U16]()._update(0, value)
_size = _size + u16_bytes


let code_point_gen =
frequency[U32]([
(range_1_size, range_1)
(range_2_size, range_2)
])
utf32_codepoint_string(code_point_gen, min, max)


command.pony

1
2
3
4
5
6
7
8
9
10
11


Returns¶

USize val

apply¶
[Source]
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.
fun box apply(
i: USize val)
: this->A ?

Parameters¶

i: USize val

Returns¶

this->A ?


[Source]
Sets a timer. Fire it if need be, schedule it on the right timing wheel,
then rearm the timer.
be apply(
timer: Timer iso)

Parameters¶

timer: Timer iso

cancel¶
[Source]
Cancels a timer.
be cancel(
timer: Timer tag)

Parameters¶

timer: Timer tag


(var data, var offset) = node()?
if (data.size() - offset) >= num_bytes then
let r =
ifdef bigendian then
data.read_u16(offset)?
else
data.read_u16(offset)?.bswap()
end

offset = offset + num_bytes
_available = _available - num_bytes

if offset < data.size() then
node()? = (data, offset)
else
_chunks.shift()?
end
r
else
// single array did not have all the bytes needed


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


let sfoo = Serialised(serialise, foo1)?
let bytes_foo: Array[U8] val = sfoo.output(output)

env.out.print("serialised representation is " +
bytes_foo.size().string() +
" bytes long")

// deserialisation
let dfoo = Serialised.input(input, bytes_foo)
let foo2 = dfoo(deserialise)? as Foo

env.out.print("(foo1 == foo2) is " + (foo1 == foo2).string())
else
env.err.print("there was an error")
end
```


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


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

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

fun shrink(i: I64): ValueAndShrink[I64] =>


x = x'

new ref create_ref(x': U32) =>
x = x'
```

But, that's probably not what you'd really want to do. Better to use the capabilities recovery facilities of Pony that we'll cover later in the [Recovering Capabilities](/reference-capabilities/recovering-capabilities.md) section.


1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171


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


552
553
554
555
556use "collections"
use pc = "collections/persistent"

primitive _CommandSpecLeaf
primitive _CommandSpecParent

type _CommandSpecType is (_CommandSpecLeaf | _CommandSpecParent )

class CommandSpec
"""
CommandSpec describes the specification of a parent or leaf command. Each
command has the following attributes:

- a name: a simple string token that identifies the command.
- a description: used in the syntax message.
- a map of options: the valid options for this command.


fun box netlink_tx_ring()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

netlink_usersock¶
[Source]


752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771


fun box mod_unsafe(
y: U8 val)
: U8 val

Parameters¶

y: U8 val

Returns¶

U8 val

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

Parameters¶


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


# Exclusion groups

By default all tests are run concurrently. This may be a problem for some
tests, eg if they manipulate an external file or use a system resource. To fix
this issue any number of tests may be put into an exclusion group.

No tests that are in the same exclusion group will be run concurrently.

Exclusion groups are identified by name, arbitrary strings may be used.
Multiple exclusion groups may be used and tests in different groups may run
concurrently. Tests that do not specify an exclusion group may be run
concurrently with any other tests.

The command line option "--sequential" prevents any tests from running
concurrently, regardless of exclusion groups. This is intended for debugging
rather than standard use.


want to continue receiving messages without yielding until you read
max_size on the TCPConnection. Return false to cause the TCPConnection
to yield now.

Includes the number of times during the current behavior, that received has
been called. This allows the notifier to end reads on a regular basis.
"""
true

fun ref expect(conn: TCPConnection ref, qty: USize): USize =>
"""
Called when the connection has been told to expect a certain quantity of
bytes. This allows nested notifiers to change the expected quantity, which
allows a lower level protocol to handle any framing (e.g. SSL).
"""
qty

fun ref closed(conn: TCPConnection ref) =>
"""
Called when the connection is closed.


fun box subc(
y: A)
: (A , Bool val)

Parameters¶

y: A

Returns¶

(A , Bool val)

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

Parameters¶


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


fun val _concat(l: List[A], acc: List[A]): List[A] =>
"""
Private helper for concat that recursively builds the new list.
"""
match l
| let cons: Cons[A] => _concat(cons.tail(), acc.prepend(cons.head()))
else
acc.reverse()
end

fun val map[B](f: {(val->A): val->B} box): List[B] =>
"""
Builds a new list by applying a function to every member of the list.
"""
_map[B](this, f, Nil[B])

fun _map[B](l: List[A], f: {(val->A): val->B} box, acc: List[B]): List[B] =>
"""
Private helper for map, recursively applying function to elements.


"""
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}`.
"""
var i = USize(0)

while i < _size do
if predicate(_ptr._apply(i), value) then
return true
end

i = i + 1
end
false

fun rfind(
value: A!,
offset: USize = -1,


Seq[A: A]¶
[Source]
A sequence of elements.
interface ref Seq[A: A]

Constructors¶
create¶
[Source]
Create a sequence, reserving space for len elements.
new ref create(
len: USize val = 0)
: Seq[A] ref^


I8 val^

max_value¶
[Source]
new val max_value()
: I8 val^

Returns¶

I8 val^

Public Functions¶
abs¶
[Source]
fun box abs()
: U8 val

Returns¶


choice = choice'
int1 = int1'
int2 = int2'

fun string(): String iso^ =>
let num1: String val = _StringifyIntArg(choice, int1)
let num2: String val = _StringifyIntArg(choice, int2)
"".join(["("; num1; ", "; num2; ")"].values())

type IntPairUnitTest is Property1UnitTest[IntPairPropertySample]

trait IntPairProperty is Property1[IntPairPropertySample]
"""
A property implementation for conveniently evaluating properties
for pairs of integers of all Pony integer types at once.

The property needs to be formulated inside the method `int_property`:

```pony


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

Returns¶

ILong val

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

Returns¶

ISize val


| `object`            | to make an object literal                                                                              |
| `primitive`         | declares a primitive type                                                                              |
| `recover`           | removes the reference capability of a variable                                                         |
| `ref`               | reference capability – object (on which function is called) is mutable                                 |
| `repeat`            | loop statement                                                                                |
| `return`            | to return early from a function                                                                        |
| `tag`               | reference capability – neither readable nor writeable, only object identity                            |
| `then`              | (1) in if conditional statement                                                                        |
|                   | (2) as a (finally) block in try                                                                        |
| `this`              | the current object                                                                                |
| `trait`             | used in nominal subtyping:  `class Foo is TraitName`                                                     |
| `trn`               | reference capability – write uniqueness, no other actor can write to the object                        |
| `try`               | error handling                                                                                |
| `type`              | to declare a type alias                                                                                |
| `until`             | loop statement                                                                                |
| `use`               | (1) using a package                                                                                |
|                   | (2) using an external library foo: use "lib:foo"                                                       |
|                   | (3) declaration of an FFI signature                                                                    |
|                   | (4) add a search path for external libraries: `use "path:/usr/local/lib"`                                |
| `var`               | declaration of mutable variable: you can rebind this name to a new value                               |


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

Parameters¶

y: I16 val

Returns¶

I16 val

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

Parameters¶


fun icmp_prec_violation():I32 => @pony_os_sockopt_option(I32(62))
fun icmp_prot_unreach():I32 => @pony_os_sockopt_option(I32(63))
fun icmp_redirect():I32 => @pony_os_sockopt_option(I32(64))
fun icmp_redir_host():I32 => @pony_os_sockopt_option(I32(65))
fun icmp_redir_hosttos():I32 => @pony_os_sockopt_option(I32(66))
fun icmp_redir_net():I32 => @pony_os_sockopt_option(I32(67))
fun icmp_redir_nettos():I32 => @pony_os_sockopt_option(I32(68))
fun icmp_source_quench():I32 => @pony_os_sockopt_option(I32(69))
fun icmp_sr_failed():I32 => @pony_os_sockopt_option(I32(70))
fun icmp_timestamp():I32 => @pony_os_sockopt_option(I32(71))
fun icmp_timestampreply():I32 => @pony_os_sockopt_option(I32(72))
fun icmp_time_exceeded():I32 => @pony_os_sockopt_option(I32(73))
fun ipctl_acceptsourceroute():I32 => @pony_os_sockopt_option(I32(74))
fun ipctl_defmtu():I32 => @pony_os_sockopt_option(I32(75))
fun ipctl_defttl():I32 => @pony_os_sockopt_option(I32(76))
fun ipctl_directedbroadcast():I32 => @pony_os_sockopt_option(I32(77))
fun ipctl_fastforwarding():I32 => @pony_os_sockopt_option(I32(78))
fun ipctl_forwarding():I32 => @pony_os_sockopt_option(I32(79))
fun ipctl_gif_ttl():I32 => @pony_os_sockopt_option(I32(80))
fun ipctl_intrdqdrops():I32 => @pony_os_sockopt_option(I32(81))


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


None val

pop¶
[Source]
Remove the highest priority value from the heap and return it. For
max-heaps, the greatest item will be returned. For min-heaps, the smallest
item will be returned.
The time complexity of this operation is O(log(n)) with respect to the size
of the heap.
fun ref pop()
: A^ ?

Returns¶

A^ ?

append¶
[Source]


Parameters¶

y: A

Returns¶

A ?

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

Parameters¶

y: A

Returns¶


bench: PonyBench tag

Returns¶

None val


"""
var cur: List[A] = this
if cur.size() <= n then return cur end
var count = n
var res: List[A] = Nil[A]
while count > 0 do
match cur
| let cons: Cons[A] =>
res = res.prepend(cons.head())
cur = cons.tail()
else
return res.reverse()
end
count = count - 1
end
res.reverse()

fun val take_while(f: {(val->A): Bool} box): List[A] =>
"""
Builds a list of elements satisfying the provided predicate until one does


Returns¶

String val

params¶
fun box params()
: PropertyParams val

Returns¶

PropertyParams val


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


let _proxy_service: String

new create(proxy_host: String, proxy_service: String) =>
_proxy_host = proxy_host
_proxy_service = proxy_service

fun apply(wrap: TCPConnectionNotify iso): TCPConnectionNotify iso^ =>
ExampleProxyNotify.create(consume wrap, _proxy_service, _proxy_service)

class iso ExampleProxyNotify is TCPConnectionNotify
// Fictional proxy implementation that has no error
// conditions, and always forwards the connection.
let _proxy_host: String
let _proxy_service: String
var _destination_host: (None | String) = None
var _destination_service: (None | String) = None
let _wrapped: TCPConnectionNotify iso

new iso create(wrap: TCPConnectionNotify iso, proxy_host: String, proxy_service: String) =>
_wrapped = wrap


fun box hash64()
: U64 val

Returns¶

U64 val

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

Returns¶

I8 val

i16¶
[Source]


Bool val

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

Parameters¶

y: I8 val

Returns¶

Bool val

ge¶
[Source]


Create a new array that is a clone of a portion of this array. The range is
exclusive and saturated.
The new array contains references to the same elements that the old array
contains, the elements themselves are not cloned.
fun box slice(
from: USize val = 0,
to: USize val = call,
step: USize val = 1)
: Array[this->A!] ref^

Parameters¶

from: USize val = 0
to: USize val = call
step: USize val = 1

Returns¶

Array[this->A!] ref^


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


new iso create(
p2: Property2[T1, T2] iso,
name': (String val | None val) = reference)
: Property2UnitTest[T1, T2] iso^

Parameters¶

p2: Property2[T1, T2] iso
name': (String val | None val) = reference

Returns¶

Property2UnitTest[T1, T2] iso^

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


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

Parameters¶

offset: USize val = 0

Returns¶

U32 val ?

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


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


y: I128 val

Returns¶

I128 val

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

Returns¶

USize val

hash64¶
[Source]


Generator[T: T]¶
[Source]
A Generator is capable of generating random values of a certain type T
given a source of Randomness
and knows how to shrink or simplify values of that type.
When testing a property against one or more given Generators,
those generators' generate methods are being called many times
to generate sample values that are then used to validate the property.
When a failing sample is found, the PonyCheck engine is trying to find a
smaller or more simple sample by shrinking it with shrink.
If the generator did not provide any shrinked samples
as a result of generate, its shrink method is called
to obtain simpler results. PonyCheck obtains more shrunken samples until


MUST be called by each long test to indicate the test has finished, unless
a timeout occurs. If you are using expect_action() then complete(true) will
be called once the last expected action has been completed via
complete_action().
The "success" parameter specifies whether the test succeeded. However if
any asserts fail the test will be considered a failure, regardless of the
value of this parameter.
Once this is called tear_down() may be called at any time.
fun box complete(
success: Bool val)
: None val

Parameters¶

success: Bool val

Returns¶

None val


fun box ip_ttl()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_unicast_if¶
[Source]


that: UnknownError val

Returns¶

Bool val

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

Parameters¶

that: UnknownError val

Returns¶


y: F32 val

Returns¶

F32 val

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

Parameters¶

y: F32 val

Returns¶


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


fun ref u128_be()
: U128 val ?

Returns¶

U128 val ?

u128_le¶
[Source]
Get a little-endian U128.
fun ref u128_le()
: U128 val ?

Returns¶

U128 val ?

i128_be¶


y: U64 val

Returns¶

I64 val

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

Parameters¶

y: U64 val

Returns¶


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64_unsafe¶
[Source]


fun box ipv6_prefer_src_tmp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_priority_11¶
[Source]


fn_key¶
[Source]
fun ref fn_key(
i: U8 val,
ctrl: Bool val,
alt: Bool val,
shift: Bool val)
: None val

Parameters¶

i: U8 val
ctrl: Bool val
alt: Bool val
shift: Bool val

Returns¶

None val


I8¶
[Source]
primitive val I8 is
SignedInteger[I8 val, U8 val] val

Implements¶

SignedInteger[I8 val, U8 val] val

Constructors¶
create¶
[Source]


fun ref set(
flag: A)
: None val

Parameters¶

flag: A

Returns¶

None val

unset¶
[Source]
Unsets the flag.
fun ref unset(
flag: A)
: None val


fun box eq(
y: I8 val)
: Bool val

Parameters¶

y: I8 val

Returns¶

Bool val

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

Parameters¶


Flag[A: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[A] val)]¶
[Source]
A flag should be a primitive with a value method that returns the bits that
represent the flag. This allows a flag to encode a single bit, or any
combination of bits.
interface val Flag[A: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |
USize val) & Integer[A] val)]

Public Functions¶
value¶
[Source]
fun box value()


: A

Parameters¶

y: A

Returns¶

A

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

Parameters¶


ANSI val^

Public Functions¶
up¶
[Source]
Move the cursor up n lines. 0 is the same as 1.
fun box up(
n: U32 val = 0)
: String val

Parameters¶

n: U32 val = 0

Returns¶

String val


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


ASCIINUL¶
[Source]
primitive val ASCIINUL

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

Returns¶

ASCIINUL val^


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


fun peek(): this->A ? =>
"""
Return the highest priority item in the heap. For max-heaps, the greatest
item will be returned. For min-heaps, the smallest item will be returned.
"""
_data(0)?

fun ref push(value: A) =>
"""
Push an item into the heap.

The time complexity of this operation is O(log(n)) with respect to the size
of the heap.
"""
_data.push(value)
_sift_up(size() - 1)

fun ref pop(): A^ ? =>
"""
Remove the highest priority value from the heap and return it. For


Note that when using unsigned integers, a negative literal wraps around so while Range[ISize](0, 10, -1) is empty as above, Range[USize](0, 10, -1) produces a single value of min or [0] here.
When using Range with floating point types (F32 and F64) inc steps < 1.0 are possible. If any arguments contains NaN, the Range is considered empty. It is also empty if the lower bound min or the step inc are +Inf or -Inf. However, if only the upper bound max is +Inf or -Inf and the step parameter inc has the same sign, then the Range is considered infinite and will iterate indefinitely.
let p_inf: F64 = F64.max_value() + F64.max_value()
let n_inf: F64 = -p_inf
let nan: F64 = F64(0) / F64(0)

let infinite_range1 = Range[F64](0, p_inf, 1)
let infinite_range2 = Range[F64](0, n_inf, -1_000_000)
infinite_range1.is_infinite() == true
infinite_range2.is_infinite() == true

for i in Range[F64](0.5, 100, nan) do
// will not be executed as `inc` is nan
end
for i in Range[F64](0.5, 100, p_inf) do
// will not be executed as `inc` is +Inf
end

class ref Range[optional A: (Real[A] val & (I8 val | I16 val | I32 val |


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


672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691


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

write¶
[Source]
Print some bytes without inserting a newline afterwards.
be write(
data: (String val | Array[U8 val] val))

Parameters¶

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

printv¶
[Source]
Print an iterable collection of ByteSeqs.
be printv(
data: ByteSeqIter val)


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


"""
Returns the number of elements in the sequence.
"""

fun apply(i: USize): this->A ?
"""
Returns the i-th element of the sequence. Raises an error if the index
is out of bounds. Note that this returns this->A, not A.
"""

fun values(): Iterator[this->A]^
"""
Returns an iterator over the elements of the sequence. Note that this
iterates over this->A, not A.
"""

interface box ReadElement[A]
"""
Used to show that a ReadSeq can return an element of a specific unmodified
type.


fun box split(
path: String val,
separator: String val = call)
: (String val , String val)

Parameters¶

path: String val
separator: String val = call

Returns¶

(String val , String val)

base¶
[Source]
Return the path after the last separator, or the whole path if there is no
separator.
If with_ext is false, the extension as defined by the ext() method


fun box ne(
y: box->A)
: Bool val

Parameters¶

y: box->A

Returns¶

Bool val

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

Parameters¶


_map.index(i)?._2

fun values(): SetValues[A, H, this->HashSet[A, H]]^ =>
"""
Return an iterator over the values.
"""
SetValues[A, H, this->HashSet[A, H]](this)

class SetValues[A, H: HashFunction[A!] val, S: HashSet[A, H] #read] is
Iterator[S->A]
"""
An iterator over the values in a set.
"""
let _set: S
var _i: USize = -1
var _count: USize = 0

new create(set: S) =>
"""
Creates an iterator for the given set.


fun box mod_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

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

Returns¶


912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931


fun box sctp_cause_missing_param()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cause_nat_missing_state¶
[Source]


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

Returns¶

U32 val

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

Parameters¶


Peek at a big-endian F32.
"""
F32.from_bits(peek_u32_be(offset)?)

fun peek_f32_le(offset: USize = 0): F32 ? =>
"""
Peek at a little-endian F32.
"""
F32.from_bits(peek_u32_le(offset)?)

fun peek_f64_be(offset: USize = 0): F64 ? =>
"""
Peek at a big-endian F64.
"""
F64.from_bits(peek_u64_be(offset)?)

fun peek_f64_le(offset: USize = 0): F64 ? =>
"""
Peek at a little-endian F64.
"""


h.dispose_when_done(property_runner)
property_runner.run()

class iso Property3UnitTest[T1, T2, T3] is UnitTest

var _prop3: ( Property3[T1, T2, T3] iso | None )
let _name: String

new iso create(p3: Property3[T1, T2, T3] iso, name': (String | None) = None) =>
_name =
match name'
| None => p3.name()
| let s: String => s
end
_prop3 = consume p3

fun name(): String => _name

fun ref apply(h: TestHelper) ? =>
let prop = ((_prop3 = None) as Property3[T1, T2, T3] iso^)


new val create()
: FormatOctal val^

Returns¶

FormatOctal val^

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

Parameters¶

that: FormatOctal val

Returns¶


112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128struct Pointer[A]
"""
A Pointer[A] is a raw memory pointer. It has no descriptor and thus can't be
included in a union or intersection, or be a subtype of any interface. Most


Parameters¶

y: ILong val

Returns¶

(ILong val , Bool val)

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

Parameters¶

y: ILong val

Returns¶


FileInfo¶
[Source]
This contains file system metadata for a path.
A symlink will report information about itself, other than the size which
will be the size of the target. A broken symlink will report as much as it
can and will set the broken flag.
class val FileInfo

Constructors¶
create¶
[Source]
This will raise an error if the FileStat capability isn't available or the
path doesn't exist.


## Example

```pony
// Generates values from `from` to 0
class ref Countdown is Iterator[USize]
var _cur: USize
var _has_next: Bool = true

new ref create(from: USize) =>
_cur = from

fun ref has_next(): Bool =>
_has_next

fun ref next(): USize =>
let elem = _cur = _cur - 1
if elem == 0 then
_has_next = false
end
elem


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


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

Returns¶

U32 val

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

Parameters¶


A

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

Parameters¶

y: A

Returns¶

A

div_unsafe¶
[Source]


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

Parameters¶

that: Ini val

Returns¶

Bool val


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


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


actor ProcessMonitor
interface ProcessNotify
class Signaled
primitive StartProcessAuth
primitive UnknownError
primitive WaitpidError
primitive WriteError


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


type Float is (F32 | F64)


fun tag expect_eq[A: (Equatable[A] #read & Stringable)]
(expect: A, actual: A, msg: String = ""): Bool
```


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


dice.pony

1
2
3
4
5
6
7
8
9
10
11


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


@_lseeki64(_fd, o, b)
else
ifdef linux then
@lseek64(_fd, o, b)
else
@lseek(_fd, o, b)
end
end

if r < 0 then
_errno = _get_error()
end
r.usize()
else
0
end

fun ref size(): USize =>
"""
Return the total length of the file.


F32 val

finite¶
[Source]
Check whether this number is finite, ie not +/-infinity and not NaN.
fun box finite()
: Bool val

Returns¶

Bool val

infinite¶
[Source]
Check whether this number is +/-infinity
fun box infinite()
: Bool val


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


"""
let _map: M
var _i: USize = -1
var _count: USize = 0

new create(map: M) =>
"""
Creates an iterator for the given map.
"""
_map = map

fun has_next(): Bool =>
"""
True if it believes there are remaining entries. May not be right if values
were added or removed from the map.
"""
_count < _map.size()

fun ref next(): (M->K, M->V) ? =>
"""


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


OpenFile val^

Public Functions¶
apply¶
[Source]
fun box apply(
from: FilePath val)
: (File ref | FileOK val | FileError val |
FileEOF val | FileBadFileNumber val | FileExists val |
FilePermissionDenied val)

Parameters¶

from: FilePath val

Returns¶

(File ref | FileOK val | FileError val |
FileEOF val | FileBadFileNumber val | FileExists val |


fun box tcp_function_name_len_max()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_keepalive¶
[Source]


y: U16 val

Returns¶

Bool val

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

Parameters¶

y: U16 val

Returns¶


Parameters¶

mode: FileMode box

Returns¶

Bool val

chown¶
[Source]
Set the owner and group for this directory. Does nothing on Windows.
fun box chown(
uid: U32 val,
gid: U32 val)
: Bool val

Parameters¶


y: I8 val

Returns¶

Bool val

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

Returns¶

USize val

hash64¶
[Source]


red_bg¶
[Source]
Red background.
fun box red_bg()
: String val

Returns¶

String val

green_bg¶
[Source]
Green background.
fun box green_bg()
: String val

Returns¶


FormatDefault¶
[Source]
primitive val FormatDefault is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


fun box ttyhook()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

pdwait¶
[Source]


HashMap[K: K, V: V, H: HashFunction[K] val]¶
[Source]
A quadratic probing hash map. Resize occurs at a load factor of 0.75. A
resized map has 2 times the space. The hash function can be plugged in to the
type to create different kinds of maps.
class ref HashMap[K: K, V: V, H: HashFunction[K] val]

Constructors¶
create¶
[Source]
Create an array with space for prealloc elements without triggering a
resize. Defaults to 6.
new ref create(


Parameters¶

y: I128 val

Returns¶

I128 val

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

Returns¶

F32 val

f64¶


let _spec: CommandSpec box
let _parent: (CommandParser box | None)

new box create(spec': CommandSpec box) =>
"""
Creates a new parser for a given command spec.
"""
_spec = spec'
_parent = None

new box _sub(spec': CommandSpec box, parent': CommandParser box) =>
_spec = spec'
_parent = parent'

fun parse(
argv: Array[String] box,
envs: (Array[String] box | None) = None)
: (Command | CommandHelp | SyntaxError)
=>
"""


pony_check.pony

1
2
3
4
5
6
7
8
9
10
11


match _escape
| _EscapeNone =>
if c == 0x1B then
_escape = _EscapeStart
_esc_buf.push(0x1B)
else
_notify(this, c)
end
| _EscapeStart =>
match c
| 'b' =>
// alt-left
_esc_mod = 3
_left()
| 'f' =>
// alt-right
_esc_mod = 3
_right()
| 'O' =>
_escape = _EscapeSS3


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


fun _u8_prime_table_size():  USize => 54

fun apply(n: A): Bool =>
if n <= 3 then return n > 1 end

let table_end: USize =
iftype A <: U8 then
_u8_prime_table_size()
else
_low_prime_table_size()
end

var table_index: USize = 0
while table_index < table_end do
let prime = _low_prime_table(table_index)
table_index = table_index + 1
if n == prime then return true end
if (n %% prime) == 0 then return false end
end


I64¶
[Source]
primitive val I64 is
SignedInteger[I64 val, U64 val] val

Implements¶

SignedInteger[I64 val, U64 val] val

Constructors¶
create¶
[Source]


# receiver type is not a subtype of target type

Suppose you made a related, but slightly different error:

```pony
class Rainbow
let colors: Array[String] = Array[String]
fun add_stripe(color: String) =>
colors.push(color)
```

In this example, rather than trying to change the value of a field, the code calls a method which attempts to modify the object referred to by the field.

The problem is very similar to that of the last section, but the error message is significantly more complicated:

```error
Error:
../a.pony:4:16: receiver type is not a subtype of target type
colors.push(color)
^


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


y: ULong val

Returns¶

ULong val ?

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

Parameters¶

y: ULong val

Returns¶


Parameters¶

iter: Iterator[val->A] ref

Returns¶

Vec[A] val

find¶
[Source]
Find the nth appearance of value from the beginning of the vector,
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 vector,
returns the first instance of value found, and uses object identity
for comparison.
fun val find(


1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191


return false
end

log(
_format_loc(loc) + "Assert " + check + " passed. " + msg
+ " Got (" + (digestof not_expect).string() + ") isnt ("
+ (digestof actual).string() + ")",
true)
true

fun assert_ne[A: (Equatable[A] #read & Stringable #read)]
(not_expect: A, actual: A, msg: String = "", loc: SourceLoc = __loc): Bool
=>
"""
Assert that the 2 given expressions are not equal.
"""
_check_ne[A]("ne", not_expect, actual, msg, loc)

fun _check_ne[A: (Equatable[A] #read & Stringable)]
(check: String, not_expect: A, actual: A, msg: String, loc: SourceLoc)


class _EmptyIterator[T]
fun ref has_next(): Bool => false
fun ref next(): T^ ? => error

primitive _Stringify
fun apply[T](t: T): (T^, String) =>
"""turn anything into a string"""
let digest = (digestof t)
let s =
match t
| let str: Stringable =>
str.string()
| let rs: ReadSeq[Stringable] =>
"[" + " ".join(rs.values()) + "]"
| (let s1: Stringable, let s2: Stringable) =>
"(" + s1.string() + ", " + s2.string() + ")"
| (let s1: Stringable, let s2: ReadSeq[Stringable]) =>
"(" + s1.string() + ", [" + " ".join(s2.values()) + "])"
| (let s1: ReadSeq[Stringable], let s2: Stringable) =>
"([" + " ".join(s1.values()) + "], " + s2.string() + ")"


MT¶
[Source]
A Mersenne Twister. This is a non-cryptographic random number generator. This
should only be used for legacy applications that require a Mersenne Twister,
otherwise use Rand.
class ref MT is
Random ref

Implements¶

Random ref


Line numbers start at 1.
"""

fun pos(): USize
"""
Character position on line.
Character positions start at 1.
"""


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

Parameters¶

y: A

Returns¶

A

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

Returns¶


fun ref has_next(): Bool =>
match _next
| _None =>
if _iter.has_next() then
_find_next()
has_next()
else
false
end
else
true
end

fun ref next(): B ? =>
match _next = _None
| let b: B =>
consume b
else
if _iter.has_next() then
_find_next()


I16 val

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

Returns¶

I32 val

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

Returns¶


fun box netrom_t4()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

pvd_config¶
[Source]


_proxy_host = proxy_host
_proxy_service = proxy_service

fun ref proxy_via(host: String, service: String): (String, String) =>
// Stash the original host & service; return the host & service
// for the proxy; indicating that the initial TCP connection should
// be made to the proxy
_destination_host = host
_destination_service = service
(_proxy_host, _proxy_service)

fun ref connected(conn: TCPConnection ref) =>
// conn is the connection to the *proxy* server. We need to ask the
// proxy server to forward this connection to our intended final
// destination.
conn.write((_destination_host + "\n").array())
conn.write((_destination_service + "\n").array())
wrapped.connected(conn)

fun ref received(conn, data, times) => _wrapped.received(conn, data, times)


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

Returns¶

Bool val

assert_is[A: A]¶
[Source]
Assert that the 2 given expressions resolve to the same instance
fun box assert_is[A: A](
expect: A,
actual: A,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val


position¶
[Source]
Return the current cursor position in the file.
fun ref position()
: USize val

Returns¶

USize val

size¶
[Source]
Return the total length of the file.
fun ref size()
: USize val

Returns¶

USize val


that: ASCIILetters val

Returns¶

Bool val

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

Parameters¶

that: ASCIILetters val

Returns¶


FormatSpec¶
[Source]
trait val FormatSpec


Type Alias For¶

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


end

fun val canonical(): FilePath ? =>
"""
Return the equivalent canonical absolute path. Raise an error if there
isn't one.
"""
_create(Path.canonical(path)?, caps)

fun val exists(): Bool =>
"""
Returns true if the path exists. Returns false for a broken symlink.
"""
try
not FileInfo(this)?.broken
else
false
end

fun val mkdir(must_create: Bool = false): Bool =>


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


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

Parameters¶

that: Fact val

Returns¶

Bool val

ne¶
[Source]
fun box ne(


# A Short Guide to Pony Error Messages

You've been through the tutorial, you've watched some videos, and now you're ready to write some Pony code. You fire up your editor, shovel coal into the compiler, and... you find yourself looking at a string of gibberish.

Don't panic! Pony's error messages try to be as helpful as possible and the ultimate goal is to improve them further. But, in the meantime, they can be a little intimidating.

This section tries to provide a short bestiary of Pony's error messages, along with a guide to understanding them.

Let's start with a simple one.


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

fun tag tests(test: PonyTest) =>
test(Property1UnitTest[String](MyStringProperty))

Run as many Properties as you wish inside one
PonyTest UnitTest using the convenience function
PonyCheck.for_all providing a
Generator, the TestHelper
and the actual property function. (Note that the property function is supplied
in a second application of the result to for_all.)

class ListReversePropertyWithinAUnitTest is UnitTest
fun name(): String => "list/reverse/forall"

fun apply(h: TestHelper) =>
let gen = recover val Generators.list_of[USize](Generators.usize()) end
PonyCheck.for_all[List[USize]](gen, h)(


fun box usize_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64_unsafe¶
[Source]


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

Parameters¶

min: I128 val = call
max: I128 val = call

Returns¶

Generator[I128 val] box


new val create()
: FormatOctalBare val^

Returns¶

FormatOctalBare val^

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

Parameters¶

that: FormatOctalBare val

Returns¶


fun box i16()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64¶
[Source]


fun box u128()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize¶
[Source]


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


fun box so_hci_raw_direction()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_incoming_cpu¶
[Source]


fun box sctp_pcb_flags_recvnxtinfo()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_recvpeererr¶
[Source]


Assert val^

Public Functions¶
apply¶
[Source]
fun box apply(
test: Bool val,
msg: String val = "")
: None val ?

Parameters¶

test: Bool val
msg: String val = ""

Returns¶

None val ?


use @cbrt[F64](x: F64)
use @"llvm.exp.f32"[F32](x: F32)
use @"llvm.exp.f64"[F64](x: F64)
use @"llvm.exp2.f32"[F32](x: F32)
use @"llvm.exp2.f64"[F64](x: F64)
use @"llvm.cos.f32"[F32](x: F32)
use @"llvm.cos.f64"[F64](x: F64)
use @"llvm.sin.f32"[F32](x: F32)
use @"llvm.sin.f64"[F64](x: F64)
use @tanf[F32](x: F32)
use @coshf[F32](x: F32)
use @sinhf[F32](x: F32)
use @tanhf[F32](x: F32)
use @acosf[F32](x: F32)
use @asinf[F32](x: F32)
use @atanf[F32](x: F32)
use @atan2f[F32](x: F32, y: F32)
use @acoshf[F32](x: F32)
use @asinhf[F32](x: F32)
use @atanhf[F32](x: F32)


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


Parameters¶

str: Pointer[U8 val] ref

Returns¶

String ref^

copy_cpointer¶
[Source]
Create a string by copying a fixed number of bytes from a pointer.
new ref copy_cpointer(
str: Pointer[U8 val] box,
len: USize val)
: String ref^

Parameters¶


SignalHandler¶
[Source]
Listen for a specific signal.
If the wait parameter is true, the program will not terminate until the SignalHandler's dispose method is called, or if the SignalNotify returns false, after handling the signal as this also disposes the SignalHandler and unsubscribes it.
actor tag SignalHandler is
AsioEventNotify tag

Implements¶

AsioEventNotify tag

Constructors¶


# Sharing

If you want to __share__ an object amongst actors, then we have to make one of the following guarantees:

1. Either _no_ actor can write to the object, in which case _any_ actor can read from it, or
2. Only _one_ actor can write to the object, in which case _other_ actors can neither read from or write to the object.

The first guarantee is exactly what `val` does. It is _globally immutable_, so we know that _no_ actor can ever write to that object. As a result, you can freely send `val` objects to other actors, without needing to give up the ability to read from that object.

__So I should use `val` when I want to share an immutable object amongst actors?__ Yes! If you don't need to share it, you can just use `ref` instead, or `box` if you want it to be immutable.

The second guarantee is what `tag` does. Not the part about only one actor writing (that's guaranteed by any mutable reference capability), but the part about not being able to read from or write to an object. That means you can freely pass `tag` objects to other actors, without needing to give up the ability to read from or write to that object.

__What's the point in sending a tag reference to another actor if it can't then read or write the fields?__ Because `tag` __can__ be used to __identify__ objects and sometimes that's all you need. Also, if the object is an actor you can call behaviours on it even though you only have a `tag`.

__So I should use `tag` when I want to share the identity of a mutable object amongst actors?__ Yes! Or, really, the identity of anything, whether it's mutable, immutable, or even an actor.


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

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

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

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

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

fun div_partial(y: ILong): ILong ? =>
_SignedPartialArithmetic.div_partial[ILong, ULong](this, y)?

fun rem_partial(y: ILong): ILong ? =>


end
else
error
end

fun ref u32_le(): U32 ? =>
"""
Get a little-endian U32.
"""
let num_bytes = U32(0).bytewidth()
if _available >= num_bytes then
let node = _chunks.head()?
(var data, var offset) = node()?
if (data.size() - offset) >= num_bytes then
let r =
ifdef littleendian then
data.read_u32(offset)?
else
data.read_u32(offset)?.bswap()
end


Called if it wasn't possible to bind the listener to an address.

It is expected to implement proper error handling. You need to opt in to
ignoring errors, which can be implemented like this:

```pony
fun ref not_listening(listen: TCPListener ref) =>
None
```
"""

fun ref closed(listen: TCPListener ref) =>
"""
Called when the listener is closed.
"""
None

fun ref connected(listen: TCPListener ref): TCPConnectionNotify iso^ ?
"""
Create a new TCPConnectionNotify to attach to a new TCPConnection for a


fun ref step_by(
n: USize val = 1)
: Iter[A!] ref

Parameters¶

n: USize val = 1

Returns¶

Iter[A!] ref

take¶
[Source]
Return an iterator for the first n elements.
Example¶
Iter[I64]([1; 2; 3; 4; 5; 6].values())
.take(3)


# Examples

Small _how do I_ examples for Pony. These will eventually find another home. Until then, they live here.


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


let data = String.from_cstring(pointer)
```

Note that the declaration for `list_pop` is still needed: if we don't add an explicit return type when calling `list_pop`, the default type will be the return type of the declaration.

When specifying a different return type for an FFI function, make sure that the new type is [compatible](#type-signature-compatibility) with the type specified in the declaration.


632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651


U32 val

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

Returns¶

I32 val

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

Returns¶


iter: Iterator[A^] ref
offset: USize val = 0
len: USize val = call

Returns¶

None val

truncate¶
[Source]
Pop tail elements until the list is len size.
If the list is already smaller than len, do nothing.
let my_list = List[String].from(["a"; "b"; "c"])
my_list.truncate(1)  // my_list is ["a"]

fun ref truncate(
len: USize val)
: None val


Parameters¶

msg: String val = "Test failed"

Returns¶

None val

assert_true¶
[Source]
Assert that the given expression is true.
fun box assert_true(
actual: Bool val,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val

Parameters¶


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

Returns¶

ISize val

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

Returns¶

U8 val


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

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

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

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

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

primitive I16 is SignedInteger[I16, U16]
new create(value: I16) => value
new from[A: (Number & Real[A] val)](a: A) => a.i16()

new min_value() => -0x8000


F64 val

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

Returns¶

I8 val

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

Returns¶


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


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


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


# Unary operators

The unary operators are handled in the same manner, but with only one operand. For example, the following expressions are equivalent:

```pony
-x
x.neg()
```

The full list of unary operators that are aliases for functions is:

---

| Operator | Method       | Description                   |
| -------- | ------------ | ----------------------------- |
| `-`        | `neg()`        | Arithmetic negation           |
| `not`      | `op_not()`     | Not, both bitwise and logical |
| `-~`       | `neg_unsafe()` | Unsafe arithmetic negation    |

---


USize val

i8¶
fun ref i8()
: I8 val

Returns¶

I8 val

i16¶
fun ref i16()
: I16 val

Returns¶

I16 val


Parameters¶

n: N

Returns¶

N

int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]¶
[Source]
A random integer in [0, n)
Not biased with small values of n like int.
fun ref int_unbiased[optional N: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |
USize val) & Real[N] val)](
n: N)
: N


cap: U64 val

Returns¶

None val

limit¶
[Source]
Limits the fd to the encoded rights.
fun box limit(
fd: I32 val)
: Bool val

Parameters¶

fd: I32 val

Returns¶


_UnsignedPartialArithmetic.add_partial[ULong](this, y)?

fun sub_partial(y: ULong): ULong ? =>
_UnsignedPartialArithmetic.sub_partial[ULong](this, y)?

fun mul_partial(y: ULong): ULong ? =>
_UnsignedPartialArithmetic.mul_partial[ULong](this, y)?

fun div_partial(y: ULong): ULong ? =>
_UnsignedPartialArithmetic.div_partial[ULong](this, y)?

fun rem_partial(y: ULong): ULong ? =>
_UnsignedPartialArithmetic.rem_partial[ULong](this, y)?

fun divrem_partial(y: ULong): (ULong, ULong) ? =>
_UnsignedPartialArithmetic.divrem_partial[ULong](this, y)?

primitive USize is UnsignedInteger[USize]
new create(value: USize) => value
new from[A: (Number & Real[A] val)](a: A) => a.usize()


op_xor[optional K: HashFunction[this->A!] val]¶
[Source]
Create a set with the elements that are in either set but not both.
fun box op_xor[optional K: HashFunction[this->A!] val](
that: this->HashSet[A, H] ref)
: HashSet[this->A!, K] ref^

Parameters¶

that: this->HashSet[A, H] ref

Returns¶

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

without[optional K: HashFunction[this->A!] val]¶
[Source]
Create a set with the elements of this that are not in that.
fun box without[optional K: HashFunction[this->A!] val](


1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131


// Not everything passed.
_env.out.print(_Color.red() + "**** FAILED: " + fail_count.string()
+ " test" + _plural(fail_count) + ", listed below:" + _Color.reset())

// Finally print our list of failed tests.
for rec in _records.values() do
rec._list_failed()
end

_env.exitcode(-1)

fun _plural(n: USize): String =>
"""
Return a "s" or an empty string depending on whether the given number is 1.
For use when printing possibly plural words, eg "test" or "tests".
"""
if n == 1 then "" else "s" end


[Source]
Create a generator for strings withing the given range,
with a minimum length of min (default: 0)
and a maximum length of max (default: 100).
fun box ascii(
min: USize val = 0,
max: USize val = 100,
range: (ASCIINUL val | ASCIIDigits val | ASCIIWhiteSpace val |
ASCIIPunctuation val | ASCIILettersLower val | ASCIILettersUpper val |
ASCIILetters val | ASCIIPrintable val | ASCIINonPrintable val |
ASCIIAll val | ASCIIAllWithNUL val) = reference)
: Generator[String val] box

Parameters¶

min: USize val = 0
max: USize val = 100
range: (ASCIINUL val | ASCIIDigits val | ASCIIWhiteSpace val |
ASCIIPunctuation val | ASCIILettersLower val | ASCIILettersUpper val |
ASCIILetters val | ASCIIPrintable val | ASCIINonPrintable val |


DoNotOptimise val^

Public Functions¶
apply[A: A]¶
[Source]
Prevent the compiler from optimising out obj and any computation it is
derived from. This doesn't prevent constant propagation.
fun box apply[A: A](
obj: A)
: None val

Parameters¶

obj: A

Returns¶

None val


"""
Shuffle the elements of the array into a random order, mutating the array.
"""
var i: USize = array.size()
try
while i > 1 do
let ceil = i = i - 1
array.swap_elements(i, int[USize](ceil))?
end
end


# Try-then blocks

In addition to an `else` error handler, a `try` command can have a `then` block. This is executed after the rest of the `try`, whether or not an error is raised or handled. Expanding our example from earlier:

```pony
try
callA()
if not callB() then error end
callC()
else
callD()
then
callE()
end
```

The `callE()` will always be executed. If `callB()` returns true then the sequence executed is `callA()`, `callB()`, `callC()`, `callE()`. If `callB()` returns false then the sequence executed is `callA()`, `callB()`, `callD()`, `callE()`.

__Do I have to have an else error handler to have a then block?__ No. You can have a `try`-`then` block without an `else` if you like.


72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91use @pony_os_addrinfo[Pointer[U8]](family: U32, host: Pointer[U8] tag,


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


if _throttled then
_throttled = false
_notify.unthrottled(this)
end

/**************************************/

fun ref getsockopt(level: I32, option_name: I32, option_max_size: USize = 4):
(U32, Array[U8] iso^) =>
"""
General wrapper for TCP 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


fun box tcp_keepalive()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_keepidle¶
[Source]


FormatHexSmall¶
[Source]
primitive val FormatHexSmall is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


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

Parameters¶

that: IniNoDelimiter val

Returns¶

Bool val


_size - index)
_set(index, value)
_size = _size + 1
_set(_size, 0)

fun cut(from: ISize, to: ISize = ISize.max_value()): String iso^ =>
"""
Returns a version of the string with the given range deleted.
Index range [`from` .. `to`) is half-open.
"""
let s = clone()
s.cut_in_place(from, to)
s

fun ref cut_in_place(from: ISize, to: ISize = ISize.max_value()) =>
"""
Cuts the given range out of the string.
Index range [`from` .. `to`) is half-open.
"""
let start = offset_to_index(from)


Parameters¶

gen1: Generator[T1] val
gen2: Generator[T2] val
h: TestHelper val

Returns¶

ForAll2[T1, T2] ref

for_all3[T1: T1, T2: T2, T3: T3]¶
[Source]
fun box for_all3[T1: T1, T2: T2, T3: T3](
gen1: Generator[T1] val,
gen2: Generator[T2] val,
gen3: Generator[T3] val,
h: TestHelper val)
: ForAll3[T1, T2, T3] ref


fun box ipv6_drop_membership()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_flowinfo¶
[Source]


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


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


end

let digit =
if (char >= '0') and (char <= '9') then
char - '0'
elseif (char >= 'A') and (char <= 'Z') then
(char - 'A') + 10
elseif (char >= 'a') and (char <= 'z') then
(char - 'a') + 10
else
break
end

if digit >= base' then
break
end

value = if minus then
(value *? base') -? digit
else


Generator[I8](
object is GenObj[I8]
fun generate(rnd: Randomness): I8^ =>
rnd.i8(min, max)

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

fun i16(
min: I16 = I16.min_value(),
max: I16 = I16.max_value())
: Generator[I16]
=>
"""
Create a generator for I16 values.
"""
let that = this
Generator[I16](
object is GenObj[I16]


# Structural subtyping

There's another kind of subtyping, where the name doesn't matter. It's called __structural subtyping__, which means that it's all about how a type is built, and nothing to do with names.

A concrete type is a member of a structural category if it happens to have all the needed elements, no matter what it happens to be called.

Structural typing is very similar to [duck typing](https://en.wikipedia.org/wiki/Duck_typing) from dynamic programming languages, except that type compatibility is determined at compile time rather than at run time. If you've used Go, you'll recognise that Go interfaces are structural types.

You do not declare structural relationships ahead of time, instead it is done by checking if a given concrete type can fulfill the required interface. For example, in the code below, we have the interface `Stringable` from the standard library. Anything can be used as a `Stringable` so long as it provides the method `fun string(): String iso^`. In our example below, `ExecveError` provides the `Stringable` interface and can be used anywhere a `Stringable` is needed. Because `Stringable` is a structural type, `ExecveError` doesn't have to declare a relationship to `Stringable`, it simply has that relationship because it has "the same shape".

```pony
interface box Stringable
"""
Things that can be turned into a String.
"""
fun string(): String iso^
"""
Generate a string representation of this object.
"""


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


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

fun box contains[optional B: (A & HasEq[A!] #read)](
a: box->B)
: Bool val

Parameters¶

a: box->B

Returns¶

Bool val

nodes¶
[Source]
Return an iterator on the nodes in the List in forward order.
let my_list = List[String].from(["a"; "b"; "c"])


672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691


fun _write_usage(w: Writer) =>
w.write("usage: " + fullname())
if _any_options() then
w.write(" [<options>]")
end
if _spec.commands().size() > 0 then
w.write(" <command>")
end
if _spec.args().size() > 0 then
for a in _spec.args().values() do
w.write(" " + a.help_string())
end
else
w.write(" [<args> ...]")
end
w.write("\n")

fun _write_options(w: Writer, options: Array[OptionSpec box] box) =>
let cols = Array[(USize,String,String)]()
for o in options.values() do