fun apply(h: TestHelper) =>
h.assert_eq[U32](2 + 2, 4)
```

Some assertions you can make with `TestHelper` are

```pony
fun tag log(msg: String, verbose: Bool = false)
be fail() =>
be assert_failed(msg: String) =>
fun tag assert_true(actual: Bool, msg: String = "") ?
fun tag expect_true(actual: Bool, msg: String = ""): Bool
fun tag assert_false(actual: Bool, msg: String = "") ?
fun tag expect_false(actual: Bool, msg: String = ""): Bool
fun tag assert_error(test: ITest, msg: String = "") ?
fun tag expect_error(test: ITest box, msg: String = ""): Bool
fun tag assert_is (expect: Any, actual: Any, msg: String = "") ?
fun tag expect_is (expect: Any, actual: Any, msg: String = ""): Bool
fun tag assert_eq[A: (Equatable[A] #read & Stringable)]
(expect: A, actual: A, msg: String = "") ?


: Generator[USize val] box

Parameters¶

min: USize val = call
max: USize val = call

Returns¶

Generator[USize val] box

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


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


fun box so_sndtimeo()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_timestamping¶
[Source]


Returns¶

U8 val

u16¶
fun box u16()
: U16 val

Returns¶

U16 val

u32¶
fun box u32()
: U32 val

Returns¶


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


FileExec¶
[Source]
primitive val FileExec

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

Returns¶

FileExec val^


Sig¶
[Source]
Define the portable signal numbers. Other signals can be used, but they are
not guaranteed to be portable.
primitive val Sig

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

Returns¶


Parameters¶

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

Returns¶

(Nil[A] val , Nil[A] val)

drop¶
[Source]
There are no elements to drop from the empty list.
fun box drop(
n: USize val)
: Nil[A] val

Parameters¶

n: USize val


Custodian¶
[Source]
A Custodian keeps a set of actors to dispose. When the Custodian is disposed,
it disposes of the actors in its set and then clears the set.
Example program¶
Imagine you have a program with 3 actors that you need to shutdown when it
receives a TERM signal. We can set up a Custodian that knows about each
of our actors and when a TERM signal is received, is disposed of.
use "bureaucracy"
use "signals"

actor Actor1
be dispose() => None // dispose of resources here.


# Compiling your program

If you are in the same directory as your program, you can just do:

```bash
ponyc
```

That tells the Pony compiler that your current working directory contains your source code, and to please compile it. If your source code is in some other directory, you can tell ponyc where it is:

```bash
ponyc path/to/my/code
```

There are other options as well, but we'll cover those later.


ULong val

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

Returns¶

USize val

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


List[A: A]¶
[Source]
A persistent list with functional transformations.
Usage¶
use "collections/persistent"

actor Main
new create(env: Env) =>
try
let l1 = Lists[U32]([2; 4; 6; 8]) // List(2, 4, 6, 8)

let empty = Lists[U32].empty() // List()


fun box rds_trans_count()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_trans_iwarp¶
[Source]


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


_map(timer') = timer'
timer'._slop(_slop)
_fire(timer')
_advance()

be cancel(timer: Timer tag) =>
"""
Cancels a timer.
"""
try
(_, let timer') = _map.remove(timer)?
timer'._cancel()

if (_map.size() == 0) and (not _event.is_null()) then
// Unsubscribe an existing event.
@pony_asio_event_unsubscribe(_event)
_event = AsioEvent.none()
end
end


A

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

Returns¶

A

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

Returns¶


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


fun box op_xor(
y: A)
: A

Parameters¶

y: A

Returns¶

A

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

Returns¶


Private helper for `map`, recursively working with `ListNode`s.
"""
try acc.push(f(ln()?)) end

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

fun flat_map[B](f: {(this->A!): List[B]} box): List[B]^ =>
"""
Builds a new `List` by applying a function to every element of the `List`,
producing a new `List` for each element, then flattened into a single `List`.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.flat_map[String]( {(s: String): List[String] => List[String].from( ["m"; s] )} )  // other_list is ["m"; "a"; "m"; "b"; "m"; c"]
```
"""


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


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


fun box ipv6_priority_9()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_priority_control¶
[Source]


"""
primitive IniIncompleteSection
primitive IniNoDelimiter

type IniError is
( IniIncompleteSection
| IniNoDelimiter
)

interface IniNotify
"""
Notifications for INI parsing.
"""
fun ref apply(section: String, key: String, value: String): Bool
"""
This is called for every valid entry in the INI file. If key/value pairs
occur before a section name, the section can be an empty string. Return
false to halt processing.
"""


auth.pony

1
2
3primitive StartProcessAuth
new create(from: AmbientAuth) =>
None


fun box ipv6_router_alert()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_rthdrdstopts¶
[Source]


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


Return an iterator over the values in the vector.
"""
VecValues[A](this)

fun val pairs(): VecPairs[A]^ =>
"""
Return an iterator over the (index, value) pairs in the vector.
"""
VecPairs[A](this)

fun _pow32(n: USize): USize =>
"""
Raise 32 to the power of n.
"""
if n == 0 then
1
else
32 << ((n - 1) * 5)
end


U32 val

setsockopt_u32¶
[Source]
Wrapper for UDP sockets to the setsockopt(2) system call where
the kernel expects an option value of a C uint32_t type / Pony
type U32.
This function returns 0 on success, else the value of errno on
failure.
fun ref setsockopt_u32(
level: I32 val,
option_name: I32 val,
option: U32 val)
: U32 val

Parameters¶

level: I32 val
option_name: I32 val


bar.Main.make().tests(test)
```

Aggregate test classes may themselves be aggregated. Every test list class may contain any combination of its own tests and aggregated lists.


F64 val) & Real[A] val)](
a: A)
: U64 val^

Parameters¶

a: A

Returns¶

U64 val^

min_value¶
[Source]
new val min_value()
: U64 val^

Returns¶


TimerNotify¶
[Source]
Notifications for timer.
interface ref TimerNotify

Public Functions¶
apply¶
[Source]
Called with the the number of times the timer has fired since this was last
called. Usually, the value of count will be 1. If it is not 1, it means
that the timer isn't firing on schedule.
For example, if your timer is set to fire every 10 milliseconds, and
count is 2, that means it has been between 20-29 milliseconds since the


U128 val

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

Returns¶

U128 val

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

Returns¶


compare.pony

1
2
3
4
5
6
7
8
9
10
11


U64 val

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

Returns¶

U64 val

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

Returns¶


ini.pony

1
2
3
4
5
6
7
8
9
10
11


(I8 val , Bool val)

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

Parameters¶

y: I8 val

Returns¶

(I8 val , Bool val)

mulc¶
[Source]


Hash and equality functions for arbitrary ByteSeq.
"""
fun hash(x: ByteSeq box): USize =>
@ponyint_hash_block(x.cpointer(), x.size())

fun hash64(x: ByteSeq box): U64 =>
@ponyint_hash_block64(x.cpointer(), x.size())

fun eq(x: ByteSeq box, y: ByteSeq box): Bool =>
if x.size() == y.size() then
@memcmp(x.cpointer(), y.cpointer(), x.size()) == 0
else
false
end


set¶
[Source]
Add a value to the set.
fun ref set(
value: A)
: None val

Parameters¶

value: A

Returns¶

None val

unset¶
[Source]


fun box ipport_reserved()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipport_userreserved¶
[Source]


USize val


flag.pony

1
2
3
4
5
6
7
8
9
10
11


u32(min.u32(), U32.max_value()).u64()
end
high or low
else
// range within U32 range
u32(min.u32(), max.u32()).u64()
end

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

Behavior is undefined if `min` > `max`.
"""
if (min == U128.min_value()) and (max == U128.max_value()) then


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

Implements¶

UnsignedInteger[ULong val] val

Constructors¶
create¶
[Source]


U128 val

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

Returns¶

ULong val

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

Returns¶


If any errors are encountered, this will return false. Otherwise, it
returns true.
"""
var section = ""
var lineno = USize(0)
var ok = true

for line in lines do
lineno = lineno + 1
var current = line.clone()
current.strip()

if current.size() == 0 then
continue
end

try
match current(0)?
| ';' | '#' =>
// Skip comments.


fun box mmap_rw()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

mmap_wx¶
[Source]


fun box ilong()
: ILong val

Returns¶

ILong val

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

Returns¶

ISize val

u8¶
[Source]


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize_unsafe¶
[Source]


fun box so_oobinline()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_passcred¶
[Source]


[Source]
Builds a new list by applying a function to every member of the list and
using the elements of the resulting lists.
fun val flat_map[B: B](
f: {(val->A): List[B]}[A, B] box)
: (Cons[B] val | Nil[B] val)

Parameters¶

f: {(val->A): List[B]}[A, B] box

Returns¶

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

for_each¶
[Source]
Applies the supplied function to every element of the list in order.
fun val for_each(


y: U64 val

Returns¶

U64 val ?

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

Parameters¶

y: U64 val

Returns¶


fun box ipctl_fastforwarding()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipctl_gif_ttl¶
[Source]


(A , A) ?

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

Returns¶

A

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


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


ILong val

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

Returns¶

ISize val

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

Returns¶


fun box sctp_peeloff()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_peer_addr_thlds¶
[Source]


Parameters¶

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

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


```

This fails to compile. The first error is:

```error
main.pony:5:8: right side must be a subtype of left side
_c = c
^
Info:
main.pony:4:17: String iso! is not a subtype of String iso: iso! is not a subtype of iso
new create(c: String iso) =>
^
```

The error is telling us that we are aliasing the `String iso` - The `!` in `iso!` means it is an alias of an existing `iso`. Looking at the code shows the problem:

```pony
new create(c: String iso) =>
_c = c
```


l = l + 1
elseif a(k.usize())? >= q then
while (a(g.usize())? > q) and (k < g) do g = g - 1 end
_swap(a, k, g)?
g = g - 1
if a(k.usize())? < p then
_swap(a, k, l)?
l = l + 1
end
end
k = k + 1
end
(l, g) = (l - 1, g + 1)
// swap pivots to final positions
_swap(a, lo, l)?
_swap(a, hi, g)?
// recursively sort 3 partitions
_sort(a, lo, l - 1)?
_sort(a, l + 1, g - 1)?
_sort(a, g + 1, hi)?


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


Returns¶

U32 val

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

Returns¶

U32 val

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


max_exp2¶
[Source]
Maximum exponent value such that (2^exponent) - 1 is representable.
fun tag max_exp2()
: I16 val

Returns¶

I16 val

max_exp10¶
[Source]
Maximum exponent value such that (10^exponent) - 1 is representable.
fun tag max_exp10()
: I16 val

Returns¶


SetValues[A: A, H: HashFunction[A!] val, S: HashSet[A, H] #read]¶
[Source]
An iterator over the values in a set.
class ref SetValues[A: A, H: HashFunction[A!] val, S: HashSet[A, H] #read] is
Iterator[S->A] ref

Implements¶

Iterator[S->A] ref

Constructors¶
create¶


"""
f64_unsafe().f32_unsafe()

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

fun addc(y: U128): (U128, Bool) =>
ifdef native128 then
@"llvm.uadd.with.overflow.i128"(this, y)
else
let overflow = this > (max_value() - y)
(this + y, overflow)
end

fun subc(y: U128): (U128, Bool) =>
ifdef native128 then


_SignedPartialArithmetic.div_partial[I64, U64](this, y)?

fun rem_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.rem_partial[I64, U64](this, y)?

fun divrem_partial(y: I64): (I64, I64) ? =>
_SignedPartialArithmetic.divrem_partial[I64, U64](this, y)?

fun fld_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.fld_partial[I64, U64](this, y)?

fun mod_partial(y: I64): I64 ? =>
_SignedPartialArithmetic.mod_partial[I64, U64](this, y)?

primitive ILong is SignedInteger[ILong, ULong]
new create(value: ILong) => value
new from[A: (Number & Real[A] val)](a: A) => a.ilong()

new min_value() =>
ifdef ilp32 or llp64 then


y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize_unsafe¶
[Source]


y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?

div_partial¶
[Source]
Divides this number by y, rounds the result towards zero.
If y is 0 or the operation overflows, this function errors.
fun box div_partial(
y: A)
: A ?


div_unsafe¶
fun box div_unsafe(
y: F64 val)
: F64 val

Parameters¶

y: F64 val

Returns¶

F64 val

divrem_unsafe¶
fun box divrem_unsafe(
y: F64 val)
: (F64 val , F64 val)


"""
StringRunes(this)

fun ref _set(i: USize, value: U8): U8 =>
"""
Unsafe update, used internally.
"""
_ptr._update(i, value)

class StringBytes is Iterator[U8]
let _string: String box
var _i: USize

new create(string: String box) =>
_string = string
_i = 0

fun has_next(): Bool =>
_i < _string.size()


: Bool val

Returns¶

Bool val

ip6¶
[Source]
Returns true for an IPv6 address.
fun box ip6()
: Bool val

Returns¶

Bool val

name¶
[Source]


Bool val

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

Parameters¶

that: FormatFix val

Returns¶

Bool val


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

Parameters¶

that: Cap val

Returns¶

Bool val

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

Parameters¶


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


fun box ipproto_trunk1()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_ttp¶
[Source]


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


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


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

Parameters¶

y: box->A

Returns¶

Bool val

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


fun ref shuffle[A: A](
array: Array[A] ref)
: None val

Parameters¶

array: Array[A] ref

Returns¶

None val


[Source]
fun box f32()
: F32 val

Returns¶

F32 val

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

Returns¶

F64 val

f32_unsafe¶


: ILong val

Returns¶

ILong val

isize¶
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
fun box u8()
: U8 val


and sorts it in place alphabetically using the default String Comparator.
It outputs:

first
second
third

use "collections"

actor Main
new create(env:Env) =>
let array = [ "third"; "second"; "first" ]
let sorted_array = Sort[Array[String], String](array)
for e in sorted_array.values() do
env.out.print(e) // prints "first \n second \n third"
end

primitive val Sort[A: Seq[B] ref, B: Comparable[B] #read]

Constructors¶


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

Parameters¶

y: I32 val

Returns¶

I32 val

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

Parameters¶


fun rel(to: String, target: String): String ? =>
"""
Returns a path such that Path.join(to, Path.rel(to, target)) == target.
Raises an error if this isn't possible.
"""
var to_clean = clean(to)
var target_clean = clean(target)

if to_clean == target_clean then
return "."
end

var to_i: ISize = 0

ifdef windows then
to_clean = abs(to_clean)
target_clean = abs(target_clean)

let to_vol = volume(to_clean)
let target_vol = volume(target_clean)


fun box so_nke()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_nofcs¶
[Source]


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


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


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

Parameters¶

offset: USize val

Returns¶

U64 val ?

read_u128[optional B: (A & Real[B] val & U8 val)]¶
[Source]


new ref create(
string: String box)
: StringBytes ref^

Parameters¶

string: String box

Returns¶

StringBytes ref^

Public Functions¶
has_next¶
[Source]
fun box has_next()
: Bool val

Returns¶


fun box sctp_auth_chunk()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_auth_delete_key¶
[Source]


end

fun ctz_unsafe(): USize =>
"""
Unsafe operation.
If this is 0, the result is undefined.
"""
ifdef ilp32 then
@"llvm.cttz.i32"(this.u32(), true).usize()
else
@"llvm.cttz.i64"(this.u64(), true).usize()
end

fun bitwidth(): USize => ifdef ilp32 then 32 else 64 end

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

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


# Subtypes of unique capabilities

When it comes to talking about unique capabilities, the situation is a bit more complex. With variables, we only had the six basic capabilities,
but we're talking about expressions here. We will have to work with aliased and unaliased forms of the capabilities.

From here, let's talk about ephemeral capabilities. Remember that the way to get an ephemeral capability is by _unaliasing_, that is, moving a value out of a
named location with `consume` or destructive read.

Subtyping here is surprisingly simple: `iso^` is a sub-capability of absolutely everything, and `trn^` is a sub-capability of `ref` and `val`. Let's go through the interesting cases again with these two:

* `iso^ <: trn^`. An `iso^` guarantees there's no readable or writable aliases, whereas `trn^` just needs no writable aliases.
* `trn^ <: ref`. A `trn^` reference can be used to read and write, which is enough for `ref`.
* `trn^ <: val`. A `trn^` reference has no writable aliases. A `val` requires global immutability, so we can forget our writable access in order to get `val`, since we know no other aliases can write.


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

Parameters¶

y: A

Returns¶

A

mod¶
[Source]
fun box mod(


return false
end
end

(_interval > 0) or ((_expiration - current) < (1 << 63))

fun _next(): U64 =>
"""
Returns the next expiration time.
"""
_expiration

fun tag _abs_expiration_time(wall: (I64, I64)): U64 =>
"""
Converts a wall-clock adjusted system time to absolute expiration time
"""
let wall_now = Time.now()
Time.nanos()
+ (((wall._1 * 1000000000) + wall._2)
- ((wall_now._1 * 1000000000) + wall_now._2)).u64()


fun ref apply(value: A) =>
let fulfill' = f = _PromiseFulFill[A, B]

try
let inner = (consume fulfill').apply(value)?

inner.next[None](
{(fulfilled: B) => p(fulfilled)},
{()? => p.reject(); error})
else
p.reject()
end
end,
object iso
var r: Reject[Promise[B]] = consume rejected
let p: Promise[B] = outer

fun ref apply() =>
let rejected' = r = RejectAlways[Promise[B]]


fun box rds_ib_abi_version()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rds_info_connections¶
[Source]


String iso^


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_u128(offset)?
else
data.read_u128(offset)?.bswap()
end

offset = offset + num_bytes
_available = _available - num_bytes

if offset < data.size() then
node()? = (data, offset)
else
_chunks.shift()?
end
r


primitive ASCIILettersLower
fun apply(): String => "abcdefghijklmnopqrstuvwxyz"

primitive ASCIILettersUpper
fun apply(): String => "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

primitive ASCIILetters
fun apply(): String => ASCIILettersLower() + ASCIILettersUpper()

primitive ASCIIPrintable
fun apply(): String =>
ASCIIDigits()
+ ASCIILetters()
+ ASCIIPunctuation()
+ ASCIIWhiteSpace()

primitive ASCIINonPrintable
fun apply(): String =>
"\x01\x02\x03\x04\x05\x06\x07\x08\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"


tmp_dir = FilePath.mkdtemp(FileAuth(h.env.root), "temp-dir")?

fun ref tear_down(h: TestHelper) =>
try
(tmp_dir as FilePath).remove()
end

fun apply(h: TestHelper)? =>
let dir = tmp_dir as FilePath
// do something inside the temporary directory

Public Types¶

interface ITest
actor PonyTest
class TestHelper
trait TestList
trait UnitTest


(I32 val , Bool val)

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

Parameters¶

y: I32 val

Returns¶

(I32 val , Bool val)

modc¶
[Source]


## Custom Deserialisation

Custom deserialisation is handled by a `fun ref _deserialise(bytes: Pointer[U8] tag)` method. This method receives a pointer to the character array that stores the serialised representation of the object (or objects) that the `Pointer` fields should point to. The programmer must copy out any bytes that will be used by the deserialised object.

The custom deserialisation method is expected to modify the values of the objects `Pointer` fields, so the fields must be declared `var` so that they can be modified.


y: U32 val

Returns¶

U32 val

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

Parameters¶

y: U32 val

Returns¶


Property4UnitTest[T1: T1, T2: T2, T3: T3, T4: T4]¶
[Source]
class iso Property4UnitTest[T1: T1, T2: T2, T3: T3, T4: T4] is
UnitTest ref

Implements¶

UnitTest ref

Constructors¶
create¶
[Source]


U16 val

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

Returns¶

U16 val

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

Returns¶


y: I16 val

Returns¶

I16 val

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

Parameters¶

y: I16 val

Returns¶


"""
Create a set with the elements of both this and that.
"""
let r = clone[K]()

for value in that.values() do
r.set(value)
end
r

fun op_and[K: HashFunction[this->A!] val = H](
that: this->HashSet[A, H])
: HashSet[this->A!, K]^
=>
"""
Create a set with the elements that are in both this and that.
"""
let r = HashSet[this->A!, K](size().min(that.size()))

for value in values() do


new val create(
value: U32 val)
: U32 val^

Parameters¶

value: U32 val

Returns¶

U32 val^

from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]¶
[Source]
new val from[A: ((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 |


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


y: U128 val

Returns¶

U128 val

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

Parameters¶

y: U128 val

Returns¶


fun box i64()
: I64 val

Returns¶

I64 val

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

Returns¶

I128 val

ilong¶
[Source]


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


UDPAuth¶
[Source]
primitive val UDPAuth

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

Parameters¶


# Precedence

We have talked about [precedence of operators](/expressions/ops.md#precedence) before, and in Pony, method calls and field accesses have higher precedence than any operators.

To sum up, in complex expressions,

1. Method calls and field accesses have higher precedence than any operators.
2. Unary operator have higher precedence than infix operators.
3. When mixing infix operators in complex expressions, we must use parentheses to specify any precedence explicitly.


1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051


// Create a TERM handler
let signal = SignalHandler(TermHandler(env), Sig.term())
// Raise TERM signal
signal.raise()

class TermHandler is SignalNotify
let _env: Env

new iso create(env: Env) =>
_env = env

fun ref apply(count: U32): Bool =>
_env.out.print("TERM signal received")
true

Signal portability¶
The Sig primitive provides support for portable signal handling across Linux,
FreeBSD and OSX. Signals are not supported on Windows and attempting to use
them will cause a compilation error.
Shutting down handlers¶


fun box tipc_max_user_msg_size()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tipc_node_recvq_depth¶
[Source]


N->A ?


new val create()
: Less val^

Returns¶

Less val^

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

Returns¶

String iso^

eq¶


Returns¶

Bool val

partition¶
[Source]
Builds a pair of Lists, the first of which is made up of the elements
satisfying the predicate and the second of which is made up of
those that do not.
let my_list = List[String].from(["a"; "b"; "c"])
(let lt_b, let gt_b) = my_list.partition( {(s: String): Bool => s < "b"} )  // lt_b is ["a"], while gt_b is ["b"; "c"]

fun box partition(
f: {(this->A!): Bool}[A] box)
: (List[this->A!] ref^ , List[this->A!] ref^)

Parameters¶

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


U64 val

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

Parameters¶

y: U64 val

Returns¶

U64 val

mul¶
[Source]


## Type inference

If the type of the array is not specified, the resulting type of the literal array expression is `Array[T] ref` where `T` (the type of the elements) is inferred as the union of all the element types:

```pony
let my_heterogenous_array =
[
U64(42)
"42"
U64.min_value()
]
```

In the above example the resulting array type will be `Array[(U64|String)] ref` because the array contains `String` and `U64` elements.

If the variable or call argument the array literal is assigned to has a type, the literal is coerced to that type:

```pony
let my_stringable_array: Array[Stringable] ref =
[


else
var i: USize = 0

while str._apply(i) != 0 do
i = i + 1
end

_size = i
_alloc = i + 1
_ptr = Pointer[U8]._alloc(_alloc)
str._copy_to(_ptr, _alloc)
end

new from_utf32(value: U32) =>
"""
Create a UTF-8 string from a single UTF-32 code point.
"""
let encoded = _UTF32Encoder.encode(value)
_size = encoded._1
_alloc = _size + 1


end

fun val concat(iter: Iterator[val->A]): Vec[A] =>
"""
Return a vector with the values of the given iterator added to the end.
"""
var v = this
for a in iter do
v = v.push(a)
end
v

fun val find(
value: val->A,
offset: USize = 0,
nth: USize = 0,
predicate: {(A, A): Bool} val = {(l: A, r: A): Bool => l is r })
: USize ?
=>
"""


primitive ASCIILettersUpper
primitive ASCIINUL
primitive ASCIINonPrintable
primitive ASCIIPrintable
primitive ASCIIPunctuation
type ASCIIRange
primitive ASCIIWhiteSpace
class CountdownIter
class ForAll
class ForAll2
class ForAll3
class ForAll4
trait GenObj
type GenerateResult
class Generator
primitive Generators
trait IntPairProperty
class IntPairPropertySample
type IntPairUnitTest
trait IntProperty


else
return SyntaxError(token, "unknown command")
end
else
match _parse_arg(token, arg_pos)
| let a: Arg =>
if a.spec()._typ_p().is_seq() then
args.upsert(a.spec().name(), a, {(x, n) => x._append(n) })
else
args.update(a.spec().name(), a)
arg_pos = arg_pos + 1
end
| let se: SyntaxError => return se
end
end
end
end

// If it's a help option, return a general or specific CommandHelp.
try


end

_size = _size + n

fun ref concat(iter: Iterator[A^], offset: USize = 0, len: USize = -1) =>
"""
Add len iterated elements to the end of the array, starting from the given
offset.
"""

var n = USize(0)

try
while n < offset do
if iter.has_next() then
iter.next()?
else
return
end


make it long enough.
* align. Specify whether fill characters should be added at the beginning or
end of the generated string, or both.
* fill. The character to pad a string with if is is shorter than width.
"""
fun apply(
str: String,
fmt: FormatDefault = FormatDefault,
prefix: PrefixDefault = PrefixDefault,
prec: USize = -1,
width: USize = 0,
align: Align = AlignLeft,
fill: U32 = ' ')
: String iso^
=>
let copy_len = str.size().min(prec.usize())
let len = copy_len.max(width.usize())
recover
let s = String(len)


fun box icmp_sr_failed()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_timestampreply¶
[Source]


Pony Standard Library¶
This package represents the test suite for the Pony standard library.
For every new package, please add a Main actor and tests to the package in a
file called 'test.pony'. Then add a corresponding use directive and a line to
the main actor constructor of this package to invoke those tests.
All tests can be run by compiling and running packages/stdlib.


isize¶
[Source]
A random integer in [ISize.min_value(), ISize.max_value()]
fun ref isize()
: ISize val

Returns¶

ISize val

int_fp_mult[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)
fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val |
U64 val | U128 val | ULong val |
USize val) & Real[N] val)](
n: N)
: N


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


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


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


fun ref getsockopt_u32(level: I32, option_name: I32): (U32, U32) =>
"""
Wrapper for UDP sockets to the `getsockopt(2)` system call where
the kernel's returned option value is a C `uint32_t` type / Pony
type `U32`.

In case of system call success, this function returns the 2-tuple:
1. The integer `0`.
2. The `*option_value` returned by the kernel converted to a Pony `U32`.

In case of system call failure, this function returns the 2-tuple:
1. The value of `errno`.
2. An undefined value that must be ignored.
"""
_OSSocket.getsockopt_u32(_fd, level, option_name)

fun ref setsockopt(level: I32, option_name: I32, option: Array[U8]): U32 =>
"""
General wrapper for UDP sockets to the `setsockopt(2)` system call.


1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031


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


where in this paragraph, ">>" means "grants at least as much authority as". In fact, the `AmbientAuth` encompasses all ambient authority and is a strictly larger authority than `NetAuth`, which grants access to the network, which is more powerful than `TCPAuth` which is restricted to the TCP protocol. Finally, `TCPConnectAuth` is good only for creating a `TCPConnection`.

This hierarchy is established by means of the constructor of the weaker authority accepting one of the stronger authorities, for example:

```pony
primitive TCPAuth
new create(from: (AmbientAuth | NetAuth)) =>
None
```

Where `TCPAuth` grants less authority than `NetAuth`. `NetAuth` can be used to create any of the derived authorities `DNSAuth`, `UDPAuth`, `TCPAuth`, `TCPListenAuth`, `TCPConnectAuth` whereas `TCPAuth` can only be used to derive `TCPListenAuth` and `TCPConnectAuth`.


Parameters¶

y: ILong val

Returns¶

ILong val

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

Parameters¶

y: ILong val

Returns¶


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


Parameters¶

that: None val

Returns¶

Bool val


: Real[A] val^

Returns¶

Real[A] val^

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

Returns¶

Real[A] val^

Public Functions¶
add¶
[Source]


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


_descr = descr'
_short = short'
(_typ, _default, _required) = _init(_StringSeqType, _StringSeq.empty())

fun name(): String =>
"""
Returns the name of this option.
"""
_name

fun descr(): String =>
"""
Returns the description for this option.
"""
_descr

fun _typ_p(): _ValueType => _typ

fun _default_p(): _Value => _default


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

Parameters¶

y: A

Returns¶

A

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


_Timer (10000ns)                        10360 ns          10238 ns      ±3.25%       10000
```
The `--noadjust` option outputs results of the overhead measured prior to each
benchmark run followed by the unadjusted benchmark result. An example of the
output of this program with `--noadjust` is as follows:
```
Benchmark                                   mean            median   deviation  iterations
Benchmark Overhead                        604 ns            603 ns      ±0.58%      300000
Nothing                                   553 ns            553 ns      ±0.30%      300000
Benchmark Overhead                        555 ns            555 ns      ±0.51%      300000
_Fib(5)                                   574 ns            574 ns      ±0.43%      300000
Benchmark Overhead                        554 ns            556 ns      ±0.48%      300000
_Fib(10)                                  822 ns            821 ns      ±0.39%      200000
Benchmark Overhead                        554 ns            553 ns      ±0.65%      300000
_Fib(20)                                30470 ns          30304 ns      ±1.55%        5000
Benchmark Overhead                        552 ns            552 ns      ±0.39%      300000
_Timer (10000 ns)                       10780 ns          10800 ns      ±3.60%       10000
```

It is recommended that a PonyBench program is compiled with the `--runtimebc`


| _None =>
if _iter.has_next() then
let a = _iter.next()?
if try f(a)? else false end then
_next = a
else
_find_next()
end
end
end
end

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


y: I128 val

Returns¶

(I128 val , I128 val) ?

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

Parameters¶

y: I128 val

Returns¶


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


### Example

```pony
Iter[I64]([1; 2; 3; 4; 5; 6].values())
.skip_while({(x) => x < 4 })
```
`4 5 6`
"""
filter_stateful(
object
var _done: Bool = false

fun ref apply(a: A!): Bool =>
if _done then return true end
if try f(a)? else false end then
false
else
_done = true
true
end


USize val

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

Parameters¶

i: USize val

Returns¶

this->A ?


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


y: I8 val

Returns¶

I8 val ?

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

Parameters¶

y: I8 val

Returns¶


192
193
194
195
196
197
198
199use @ntohl[U32](netlong: U32)
use @ntohs[U16](netshort: U16)
use @pony_os_ipv4[Bool](addr: NetAddress tag)
use @pony_os_ipv6[Bool](addr: NetAddress tag)
use @ponyint_address_length[U32](addr: NetAddress tag)
use @pony_os_nameinfo[Bool](addr: NetAddress tag,
host: Pointer[Pointer[U8] iso] tag, serv: Pointer[Pointer[U8] iso] tag,
reverse_dns: Bool, service_name: Bool)

class val NetAddress is Equatable[NetAddress]
"""
Represents an IPv4 or IPv6 address. The family field indicates the address
type. The addr field is either the IPv4 address or the IPv6 flow info. The


(consume s, shrink_iter)
end)

fun _trim_codepoints(s: String, trim_to: USize): String =>
recover val
Iter[U32](s.runes())
.take(trim_to)
.fold[String ref](
String.create(trim_to),
{(acc, cp) => acc.>push_utf32(cp) })
end

fun unicode(
min: USize = 0,
max: USize = 100)
: Generator[String]
=>
"""
Create a generator for unicode strings,
with a minimum length of `min` codepoints (default: 0)


fun box u128_unsafe()
: U128 val

Returns¶

U128 val

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

Returns¶

ULong val

usize_unsafe¶
[Source]


ILong val ?

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

Parameters¶

y: ILong val

Returns¶

ILong val ?

shl¶


for elem in iter do
if i >= size then break end

result.push(consume elem)
i = i + 1
end
// create shrink_iter with smaller seqs and elements generated from _gen.value_iter
let shrink_iter =
Iter[USize](CountdownIter(size, min)) //Range(size, min, -1))
// .skip(1)
.map_stateful[S^]({
(s: USize): S^ =>
let res = recover iso S.create(s) end
let s_iter = _gen.value_iter(rnd)
var j = USize(0)

for s_elem in s_iter do
if j >= s then break end
res.push(consume s_elem)
j = j + 1


fun box divrem(
y: U8 val)
: (U8 val , U8 val)

Parameters¶

y: U8 val

Returns¶

(U8 val , U8 val)

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

Parameters¶


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


Parameters¶

seq: ReadSeq[U8 val] box
offset: USize val = 0
len: USize val = call

Returns¶

None val

concat¶
[Source]
Add len iterated bytes to the end of the string, starting from the given
offset.
fun ref concat(
iter: Iterator[U8 val] ref,
offset: USize val = 0,
len: USize val = call)


be _event_notify(event: AsioEventID, flags: U32, arg: U32) =>
"""
When the event fires, read from stdin.
"""
if AsioEvent.disposable(flags) then
@pony_asio_event_destroy(event)
elseif (_event is event) and AsioEvent.readable(flags) then
_read()
end

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

fun ref _read(): Bool =>
"""
Read a chunk of data from stdin. Read a maximum of _chunk_size bytes, send
ourself a resume message and stop reading to avoid starving other actors.


 Example program

```pony
use "format"

actor Main
fun disp(desc: String, v: I32, fmt: FormatInt = FormatDefault): String =>
Format(desc where width = 10)
+ ":"
+ Format.int[I32](v where width = 10, align = AlignRight, fmt = fmt)

new create(env: Env) =>
try
(let x, let y) = (env.args(1)?.i32()?, env.args(2)?.i32()?)
env.out.print(disp("x", x))
env.out.print(disp("y", y))
env.out.print(disp("hex(x)", x, FormatHex))
env.out.print(disp("hex(y)", y, FormatHex))
env.out.print(disp("x * y", x * y))
else


# Actors

An __actor__ is similar to a __class__, but with one critical difference: an actor can have __behaviours__.


Unsafe operation.
If this is 0, the result is undefined.
"""

fun ctz_unsafe(): A
"""
Count trailing zeroes.

Unsafe operation.
If this is 0, the result is undefined.
"""

fun bitwidth(): A

fun bytewidth(): USize

fun string(): String iso^ =>
_ToString._u64(u64(), false)

trait val FloatingPoint[A: FloatingPoint[A] val] is Real[A]


if (lineblocks > 0) and (blocks == lineblocks) then
out.append(linesep)
blocks = 0
end
end

if srclen >= 1 then
let in1 = data(i)?
let in2 = if srclen == 2 then data(i + 1)? else 0 end

let out1 = in1 >> 2
let out2 = ((in1 and 0x03) << 4) + (in2 >> 4)
let out3 = (in2 and 0x0f) << 2

out.push(_enc_byte(out1, at62, at63)?)
out.push(_enc_byte(out2, at62, at63)?)

if srclen == 2 then
out.push(_enc_byte(out3, at62, at63)?)
else


fun box u8()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32¶
[Source]


bit_reverse¶
[Source]
Reverse the order of the bits within the integer.
For example, 0b11101101 (237) would return 0b10110111 (183).
fun box bit_reverse()
: A

Returns¶

A

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

Returns¶

A


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


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

Parameters¶

y: U16 val

Returns¶

U16 val

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

Returns¶


The result has the sign of the divisor.
fun box mod(
y: A)
: A

Parameters¶

y: A

Returns¶

A

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


y: I128 val

Returns¶

Bool val

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

Parameters¶

y: I128 val

Returns¶


XorOshiro128Plus¶
[Source]
This is an implementation of xoroshiro128+, as detailed at:
http://xoroshiro.di.unimi.it
This is currently the default Rand implementation.
class ref XorOshiro128Plus is
Random ref

Implements¶

Random ref


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


12
13
14
15
16
17
18
19
20
21
22class ref Poperator[T] is Iterator[T^]
"""
Iterate over a [Seq](builtin-Seq.md) descructively by `pop`ing its elements.

Once `has_next()` returns `false`, the [Seq](builtin-Seq.md) is empty.

Nominee for the annual pony class-naming awards.
"""

let _seq: Seq[T]


1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271


fun box so_exclusiveaddruse()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_group_id¶
[Source]


Bool val

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

Parameters¶

y: U64 val

Returns¶

Bool val

hash64¶
[Source]


let lead_char = _ptr._apply(index)
let base_char = _ptr._apply(index + 1) and not 0x20

if (lead_char == '0') and (base_char == 'B') then
return (2, 2)
end

if (lead_char == '0') and (base_char == 'X') then
return (16, 2)
end

// No base specified, default to decimal
(10, 0)

fun f32(offset: ISize = 0): F32 ? =>
"""
Convert this string starting at the given offset
to a 32-bit floating point number ([F32](builtin-F32.md)).

This method errors if this string cannot be parsed to a float,


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


FormatInt¶
[Source]
type FormatInt is
(FormatDefault val | FormatUTF32 val | FormatBinary val | FormatBinaryBare val | FormatOctal val | FormatOctalBare val | FormatHex val | FormatHexBare val | FormatHexSmall val | FormatHexSmallBare val)

Type Alias For¶

(FormatDefault val | FormatUTF32 val | FormatBinary val | FormatBinaryBare val | FormatOctal val | FormatOctalBare val | FormatHex val | FormatHexBare val | FormatHexSmall val | FormatHexSmallBare val)


fun box hash64()
: U64 val

Returns¶

U64 val

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

Returns¶

I8 val

i16¶
[Source]


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

offset = offset + num_bytes
_available = _available - num_bytes

if offset < data.size() then
node()? = (data, offset)
else
_chunks.shift()?
end
r


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


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


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


end
end
end
envsmap


fun box ipv6_rthdrdstopts()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_tlv_hao¶
[Source]


ILong val

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

Returns¶

ISize val

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

Returns¶


fun box sctp_had_no_tcb()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_heartbeat_request¶
[Source]


Greater¶
[Source]
primitive val Greater is
Equatable[(Less val | Equal val | Greater val)] ref

Implements¶

Equatable[(Less val | Equal val | Greater val)] ref

Constructors¶
create¶
[Source]


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


n = n + 1
end
end

n = 0

// If a concrete len is specified, we take the caller at their word
// and reserve that much space, even though we can't verify that the
// iterator actually has that many elements available. Reserving ahead
// of time lets us take a fast path of direct pointer access.
if len != -1 then
reserve(_size + len)

try
while n < len do
if iter.has_next() then
_ptr._update(_size + n, iter.next()?)
else
break
end


Bool val


"""
@"llvm.cttz.i16"(this.u16(), true)

fun bitwidth(): U16 => 16

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

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

fun fld(y: I16): I16 =>
_SignedArithmetic.fld[I16, U16](this, y)

fun fld_unsafe(y: I16): I16 =>
_SignedUnsafeArithmetic.fld_unsafe[I16, U16](this, y)

fun mod(y: I16): I16 =>
_SignedArithmetic.mod[I16, U16](this, y)

fun mod_unsafe(y: I16): I16 =>


break
end
until (i = i - 1) == 0 end

truncate(truncate_at)
end

fun ref lstrip(s: String box = " \t\v\f\r\n") =>
"""
Remove all leading characters within the string that are in s. By default,
leading whitespace is removed.
"""
if _size > 0 then
let chars = Array[U32](s.size())
var i = USize(0)

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


complete_run¶
[Source]
Complete a property run.
This behaviour is called from the PropertyHelper
or from the actor itself.
be complete_run(
round: (_Shrink val | _Run val),
success: Bool val)

Parameters¶

round: (_Shrink val | _Run val)
success: Bool val

run¶
[Source]
be run()


32
33
34
35
36
37
38
39actor FileStream is OutStream
"""
Asynchronous access to a File object. Wraps file operations print, write,
printv and writev. The File will be disposed through File._final.
"""
let _file: File

new create(file: File iso) =>
_file = consume file

be print(data: ByteSeq) =>
"""
Print some bytes and insert a newline afterwards.


fun box bright_magenta()
: String val

Returns¶

String val

bright_cyan¶
[Source]
Bright cyan text.
fun box bright_cyan()
: String val

Returns¶

String val

bright_grey¶


fun box powi(
y: I32 val)
: F64 val

Parameters¶

y: I32 val

Returns¶

F64 val

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

Returns¶


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


652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671


ULong val ?

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

Parameters¶

y: ULong val

Returns¶

ULong val ?

divrem_partial¶
[Source]


fun box sock_maxaddrlen()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sock_raw¶
[Source]


error
end
path = tmp_path

new val mkdtemp(
base: (FileAuth | FilePath),
prefix: String = "",
caps': FileCaps val = recover val FileCaps .> all() end) ?
=>
"""
Create a temporary directory and returns a path to it. The directory's name
will begin with `prefix`.

If `FileAuth` is provided, the resulting `FilePath` will
be relative to the program's working directory. Otherwise, it will be
relative to the existing `FilePath`, and the existing `FilePath` must be a
prefix of the resulting path.

The resulting `FilePath` will have capabilities that are the intersection
of the supplied capabilities and the capabilities on the base.


_stdin.begin(this)
_stdout.begin(this)
_stderr.begin(this)
else
_notifier.failed(this, ProcessError(ForkError))
return
end

// Asio is not wired up for Windows, so use a timer for now.
ifdef windows then
_setup_windows_timers()
end
_notifier.created(this)

be print(data: ByteSeq) =>
"""
Print some bytes and append a newline.
"""
if not _done_writing then


fun value(): U64 => 2

primitive RDTSCP
fun value(): U64 => 4

type Features is Flags[(SSE | AVX | RDTSCP)]

Type parameter B is the underlying field used to store the flags.
"""
var _value: B = 0

new iso create(value': B = 0) =>
"""
Create a Flags instance with an optional initial value.
Default is 0 (no flags set).
"""
_value = value'

fun value(): B =>
"""


(A , A) ?

fld_partial¶
[Source]
Floored integer division, rounded towards negative infinity.
If y is 0 or the operation overflows, this function errors
fun box fld_partial(
y: A)
: A ?

Parameters¶

y: A

Returns¶

A ?


F64 val

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

Parameters¶

that: box->A

Returns¶

(Less val | Equal val | Greater val)


new val create()
: PrefixSign val^

Returns¶

PrefixSign val^

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

Parameters¶

that: PrefixSign val

Returns¶


A

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

Returns¶

USize val

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

Returns¶


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447interface ITest
fun apply() ?

class val TestHelper
"""


fun box tcpopt_multipath()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcpopt_pad¶
[Source]


y: ULong val

Returns¶

ULong val

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

Parameters¶

y: ULong val

Returns¶


while (_read_buf_offset >= _expect) and (_read_buf_offset > 0) do
// get data to be distributed and update `_read_buf_offset`
let chop_at = if _expect == 0 then _read_buf_offset else _expect end
(let data, _read_buf) = (consume _read_buf).chop(chop_at)
_read_buf_offset = _read_buf_offset - chop_at

// increment max reads
received_called = received_called + 1

// check if we should yield to let another actor run
if (not _notify.received(this, consume data,
received_called))
or (received_called >= _max_received_called)
then
_read_again()
_reading = false
return
end
end


fun box kqueue_event()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

ttyhook¶
[Source]


fun box bytewidth()
: USize val

Returns¶

USize val

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

Parameters¶

y: USize val

Returns¶


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


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


: NetAddress val

Returns¶

NetAddress val

getsockopt¶
[Source]
General wrapper for UDP sockets to the getsockopt(2) system call.
The caller must provide an array that is pre-allocated to be
at least as large as the largest data structure that the kernel
may return for the requested option.
In case of system call success, this function returns the 2-tuple:
1. The integer 0.
2. An Array[U8] of data returned by the system call's void *
4th argument.  Its size is specified by the kernel via the
system call's sockopt_len_t * 5th argument.
In case of system call failure, this function returns the 2-tuple:
1. The value of errno.


[Source]
fun box op_and(
y: ISize val)
: ISize val

Parameters¶

y: ISize val

Returns¶

ISize val

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


U64 val

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

Returns¶

U128 val

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

Returns¶


fun box apply(
str: String val,
fmt: FormatDefault val = reference,
prefix: PrefixDefault val = reference,
prec: USize val = call,
width: USize val = 0,
align: (AlignLeft val | AlignRight val | AlignCenter val) = reference,
fill: U32 val = 32)
: String iso^

Parameters¶

str: String val
fmt: FormatDefault val = reference
prefix: PrefixDefault val = reference
prec: USize val = call
width: USize val = 0
align: (AlignLeft val | AlignRight val | AlignCenter val) = reference
fill: U32 val = 32


var steps = nth + 1

while i < _size do
var j: USize = 0

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

if same and ((steps = steps - 1) == 1) then
return i.isize()
end


Version 0 of the capsicum cap_rights_t structure.
"""
var _r0: U64 = 0
var _r1: U64 = 0

new create() =>
"""
Initialises with no rights.
"""
clear()

new from(caps: FileCaps box) =>
"""
Initialises with the rights from a FileCaps.
"""
clear()

if caps(FileCreate) then set(Cap.creat()) end
if caps(FileChmod) then set(Cap.fchmod()) end
if caps(FileChown) then set(Cap.fchown()) end


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


Parameters¶

y: box->A

Returns¶

Bool val

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

Parameters¶

y: box->A

Returns¶


fun tag _unsafe(): Pointer[A] ref =>
"""
Unsafe change in reference capability.
"""
compile_intrinsic

fun _convert[B](): this->Pointer[B] =>
"""
Convert from Pointer[A] to Pointer[B].
"""
compile_intrinsic

fun _apply(i: USize): this->A =>
"""
Retrieve index i.
"""
compile_intrinsic

fun ref _update(i: USize, value: A!): A^ =>
"""


512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531


fun apply(out: OutStream, issue: Promise[Issue]) =>
issue.next[None](ActuallyPrintIssueTitle~apply(out))

primitive ActuallyPrintIssueTitle
fun apply(out: OutStream, issue: Issue) =>
out.print(issue.title())
```

That will work, however, it is kind of awful. When looking at:

```pony
let repo: Promise[Repoository] =
GitHub("my token").get_repo("ponylang/ponyc")
let issue = Promise[Promise[Issue]] =
repo.next[Promise[Issue]](FetchIssue~apply(1))
issue.next[None](PrintIssueTitle~apply(env.out))
```

it can be hard to follow what is going on. We can only tell what is
happening because we gave `PrintIssueTitle` a very misleading name; it


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

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

fun usize(
min: USize = USize.min_value(),
max: USize = USize.max_value())
: Generator[USize]
=>


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.
let array = Array[U8](4)              // []
array.insert(0, 0xDE)?                // prepend: [0xDE]
array.insert(array.size(), 0xBE)?     // append:  [0xDE; 0xBE]
array.insert(1, 0xAD)?                // insert:  [0xDE; 0xAD; 0xBE]
array.insert(array.size() + 1, 0xEF)? // error

fun ref insert(
i: USize val,
value: A)
: None val ?

Parameters¶

i: USize val


Iter[I64]([1; 2; 3; 4; 5; 6].values())
.take_while({(x) => x < 4 })

1 2 3
fun ref take_while(
f: {(A!): Bool ?}[A] box)
: Iter[A!] ref^

Parameters¶

f: {(A!): Bool ?}[A] box

Returns¶

Iter[A!] ref^

unique[optional H: HashFunction[A] val]¶
[Source]
Return an iterator that filters out elements that have already been


eq¶
[Source]
Determine equality between two keys with the same hash. This is done with
viewpoint adapted aliases to allow data structures to determine equality
in a box fun without consuming keys.
fun box eq(
x: box->A!,
y: box->A!)
: Bool val

Parameters¶

x: box->A!
y: box->A!

Returns¶

Bool val


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


Returns¶

USize val ?

clone¶
[Source]
Clone the array.
The new array contains references to the same elements that the old array
contains, the elements themselves are not cloned.
fun box clone()
: Array[this->A!] ref^

Returns¶

Array[this->A!] ref^

slice¶
[Source]


else
error
end

fun ref rewind() =>
_idx = _min

fun is_infinite(): Bool =>
_infinite

fun is_empty(): Bool =>
_empty


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


other: Iterator[A] ref)
: Iter[A!] ref

Parameters¶

other: Iterator[A] ref

Returns¶

Iter[A!] ref

interleave_shortest¶
[Source]
Return an iterator that alternates the values of the original iterator and
the other until one of them runs out.
Example¶
Iter[USize](Range(0, 4))
.interleave_shortest(Range(4, 6))


path
end

fun cwd(): String =>
"""
Returns the program's working directory. Setting the working directory is
not supported, as it is not concurrency-safe.
"""
recover String.from_cstring(@pony_os_cwd()) end

fun abs(path: String): String =>
"""
Returns a cleaned, absolute path.
"""
if is_abs(path) then
clean(path)
else
join(cwd(), path)
end


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


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


endif
```

Note the use of `extern "C"`. If the library is built as C++ then we need to tell the compiler not to mangle the function name, otherwise, Pony won't be able to find it. For libraries built as C, this is not needed, of course.

The implementation of the previous header would be something like:

```c


fun box sctp_cause_unsupported_hmacid()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cc_hstcp¶
[Source]


nth: USize val = 0)
: Bool val

Parameters¶

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

Returns¶

Bool val

count¶
[Source]
Counts the non-overlapping occurrences of s in the string.
fun box count(
s: String box,
offset: ISize val = 0)


Nanos val^

Public Functions¶
from_seconds¶
[Source]
fun box from_seconds(
t: U64 val)
: U64 val

Parameters¶

t: U64 val

Returns¶

U64 val


1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491


match _next
| let  next': ListNode[A] =>
next'._prev = that
else
list'._set_tail(that)
end

that._list = list'
that._prev = this
that._next = _next
_next = that
list'._increment()
end
in_list

fun ref remove() =>
"""
Remove a node from a list.


Parameters¶

data: ByteSeqIter val

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

Parameters¶

data: ByteSeqIter val

done_writing¶
[Source]
Set the _done_writing flag to true. If _pending is empty we can close the


Return this Map without the given key.
"""
try
remove(key)?
else
this
end

fun val keys(): MapKeys[K, V, H] => MapKeys[K, V, H](this)

fun val values(): MapValues[K, V, H] => MapValues[K, V, H](this)

fun val pairs(): MapPairs[K, V, H] => MapPairs[K, V, H](this)

fun _root_node(): _MapSubNodes[K, V, H] => _root

class MapKeys[K: Any #share, V: Any #share, H: mut.HashFunction[K] val]
embed _pairs: MapPairs[K, V, H]

new create(m: HashMap[K, V, H]) => _pairs = MapPairs[K, V, H](m)


StringRunes¶
[Source]
class ref StringRunes is
Iterator[U32 val] ref

Implements¶

Iterator[U32 val] ref

Constructors¶
create¶
[Source]


Returns¶

USize val

clear¶
[Source]
Discard all pending data.
fun ref clear()
: None val

Returns¶

None val

append¶
[Source]
Add a chunk of data.
fun ref append(


Returns¶

V!

remove¶
[Source]
Delete a value from the map and return it. Raises an error if there was no
value for the given key.
fun ref remove(
key: box->K!)
: (K^ , V^) ?

Parameters¶

key: box->K!

Returns¶


# Example code

```pony
use "debug"

actor Main
new create(env: Env) =>
Debug.out("This will only be seen when configured for debug info")
env.out.print("This will always be seen")
```
"""
use @fprintf[I32](stream: Pointer[U8] tag, fmt: Pointer[U8] tag, ...)
use @pony_os_stdout[Pointer[U8]]()
use @pony_os_stderr[Pointer[U8]]()

primitive DebugOut
primitive DebugErr

type DebugStream is (DebugOut | DebugErr)


(U8 val , U8 val) ?

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

Parameters¶

y: U8 val

Returns¶

U8 val

shr¶
[Source]


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

Parameters¶

y: U32 val

Returns¶

U32 val

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

Parameters¶


error
else
recover String.from_cstring(consume cstring) end
end

fun is_list_sep(c: U8): Bool =>
"""
Determine if a byte is a path list separator.
"""
ifdef windows then c == ';' else c == ':' end

fun list_sep(): String =>
"""
Return the path list separator as a string.
"""
ifdef windows then ";" else ":" end

fun split_list(path: String): Array[String] iso^ =>
"""
Separate a list of paths into an array of cleaned paths.


OpenFile¶
[Source]
Open a File for read only.
primitive val OpenFile

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

Returns¶


"""
_file.print(data)

be write(data: ByteSeq) =>
"""
Print some bytes without inserting a newline afterwards.
"""
_file.write(data)

be printv(data: ByteSeqIter) =>
"""
Print an iterable collection of ByteSeqs.
"""
_file.printv(data)

be writev(data: ByteSeqIter) =>
"""
Write an iterable collection of ByteSeqs.
"""
_file.writev(data)


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


fun box tcp_mss()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_mss_desired¶
[Source]


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


fun ref trim_in_place(from: USize = 0, to: USize = -1) =>
"""
Trim the string to a portion of itself, covering `from` until `to`.
Unlike slice, the operation does not allocate a new string nor copy
elements.
"""
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


end
_create(root', recover Array[A] end, size', _depth)
end

fun val pop(): Vec[A] ? =>
"""
Return a vector with the value at the end removed.
"""
// root is popped when tail is empty
let size' = _size - 1
if _tail.size() > 0 then
let tail = _tail.trim(0, _tail.size() - 1)
_create(_root, tail, size', _depth)
else
(let root, var tail) = (_root as _VecNode[A]).pop(_depth, size')?
tail = tail.trim(0, tail.size() - 1)
if _depth == 0
then _create(None, tail, size', -1)
else _create(root, tail, size', _depth)
end


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


fun box acl_get()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

kqueue_change¶
[Source]


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


U128 val

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

Returns¶

ULong val

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

Returns¶


fun cpointer(offset: USize = 0): Pointer[U8] tag =>
"""
Returns a C compatible pointer to the underlying string allocation.
"""
_ptr._offset(offset)

fun cstring(): Pointer[U8] tag =>
"""
Returns a C compatible pointer to a null-terminated version of the
string, safe to pass to an FFI function that doesn't accept a size
argument, expecting a null-terminator. If the underlying string
is already null terminated, this is returned; otherwise the string
is copied into a new, null-terminated allocation.
"""
if is_null_terminated() then
return _ptr
end

let ptr = Pointer[U8]._alloc(_size + 1)
_ptr._copy_to(ptr._unsafe(), _size)


1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711


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


n: USize val

Returns¶

Vec[A] val ?

push¶
[Source]
Return a vector with the value added to the end.
fun val push(
value: val->A)
: Vec[A] val

Parameters¶

value: val->A

Returns¶


fun box hash64()
: U64 val

Returns¶

U64 val

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

Returns¶

I8 val

i16¶
[Source]


: ILong val

Returns¶

ILong val

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

Returns¶

ISize val

int_fp_mult[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]¶
[Source]
fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val |


generate_value¶
[Source]
Simply generate a value and ignore any possible
shrink values.
fun box generate_value(
rnd: Randomness ref)
: T^ ?

Parameters¶

rnd: Randomness ref

Returns¶

T^ ?

generate_and_shrink¶


// Ignore any tests that satisfy our "exclude" filter
if (_exclude != "") and name.at(_exclude, 0) then
return
end

// Ignore any tests that don't satisfy our "only" filter
if (_only != "") and (not name.at(_only, 0)) then
return
end

// Ignore tests when label arg is set and test label doesn't match
if (_label != "") and (_label != test.label()) then
return
end

_any_found = true

if _list_only then
// Don't actually run tests, just list them
_env.out.print(name)


Bool val

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

Parameters¶

y: ILong val

Returns¶

Bool val

gt¶


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


fun box hash()
: USize val

Returns¶

USize val

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

Returns¶

U64 val

string¶
[Source]


# Control structures are expressions

The big difference for control structures between Pony and other languages is that in Pony everything is an expression. In languages like C++ and Java `if` is a statement, not an expression. This means that you can't have an `if` inside an expression, there has to be a separate conditional operator '?'.

In Pony control flow statements like this are all expressions that hand back a value. Your `if` statement hands you back a value. Your `for` loop (which we'll get to a bit later) hands you back a value.

This means you can use `if` directly in a calculation:

```pony
x = 1 + if lots then 100 else 2 end
```

This will give __x__ a value of either 3 or 101, depending on the variable __lots__.

If the `then` and `else` branches of an `if` produce different types then the `if` produces a __union__ of the two.

```pony
var x: (String | Bool) =
if friendly then
"Hello"


// Don't call _complete_writes, as Windows will see this as a
// closed connection.
ifdef not windows then
if _pending_writes() then
// Sent all data; release backpressure.
_release_backpressure()
end
end
else
// The connection failed, unsubscribe the event and close.
@pony_asio_event_unsubscribe(event)
@pony_os_socket_close(fd)
_notify_connecting()
end
else
// There is a possibility that a non-Windows system has
// already unsubscribed this event already.  (Windows might
// be vulnerable to this race, too, I'm not sure.) It's a
// bug to do a second time.  Look at the disposable status
// of the event (not the flags that this behavior's args!)


| 1    | 8     |
| 8    | 8     |
| 9    | 16    |
| 16   | 16    |
| 17   | 32    |

Call the `compact()` method to ask the GC to reclaim unused space. There are
no guarantees that the GC will actually reclaim any space.
"""
var _size: USize
var _alloc: USize
var _ptr: Pointer[A]

new create(len: USize = 0) =>
"""
Create an array with zero elements, but space for len elements.
"""
_size = 0

if len > 0 then


fun box neg()
: ULong val

Returns¶

ULong val

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

Parameters¶

y: ULong val

Returns¶


y: I64 val

Returns¶

I64 val

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

Parameters¶

y: I64 val

Returns¶


fun ref apply(term: ANSITerm ref, input: U8) =>
None

fun ref up(ctrl: Bool, alt: Bool, shift: Bool) =>
None

fun ref down(ctrl: Bool, alt: Bool, shift: Bool) =>
None

fun ref left(ctrl: Bool, alt: Bool, shift: Bool) =>
None

fun ref right(ctrl: Bool, alt: Bool, shift: Bool) =>
None

fun ref delete(ctrl: Bool, alt: Bool, shift: Bool) =>
None

fun ref insert(ctrl: Bool, alt: Bool, shift: Bool) =>
None


mkdtemp¶
[Source]
Create a temporary directory and returns a path to it. The directory's name
will begin with prefix.
If FileAuth is provided, the resulting FilePath will
be relative to the program's working directory. Otherwise, it will be
relative to the existing FilePath, and the existing FilePath must be a
prefix of the resulting path.
The resulting FilePath will have capabilities that are the intersection
of the supplied capabilities and the capabilities on the base.
new val mkdtemp(
base: (FileAuth val | FilePath val),
prefix: String val = "",
caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover)
: FilePath val^ ?

Parameters¶

base: (FileAuth val | FilePath val)


y: A)
: A

Parameters¶

y: A

Returns¶

A

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

Parameters¶


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

Parameters¶

y: U128 val

Returns¶

U128 val

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

Parameters¶


fun box ipproto_ipip()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_ipv4¶
[Source]


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

Parameters¶

that: EraseRight val

Returns¶

Bool val


fun box has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Returns the next value, or raises an error if there isn't one. If values
are added during iteration, this may not return all values.
fun ref next()
: M->V ?

Returns¶

M->V ?


: ULong val

Returns¶

ULong val

usize_unsafe¶
fun box usize_unsafe()
: USize val

Returns¶

USize val

f32_unsafe¶
fun box f32_unsafe()
: F32 val


# Keywords

This listing explains the usage of every Pony keyword.

| Keyword           | Usage                                                                                |
| ----------------- | ------------------------------------------------------------------------------------------------------ |
| `actor`             | defines an actor                                                                                |
| `as`                | conversion of a value to another Type (can raise an error)                                             |
| `be`                | behavior, executed asynchronously                                                                      |
| `box`               | default reference capability – object is readable, but not writable                                    |
| `break`             | to step out of a loop statement                                                                        |
| `class`             | defines a class                                                                                |
| `compile_error`     | will provoke a compile error                                                                           |
| `compile_intrinsic` | implementation is written in C and not available as Pony code                                          |
| `continue`          | continues a loop with the next iteration                                                               |
| `consume`           | move a value to a new variable, leaving the original variable empty                                    |
| `digestof`          | create a `USize` value that summarizes the Pony object, similar to a Java object's `hashCode()` value. |
| `do`                | loop statement, or after a with statement                                                              |
| `else`              | conditional statement in if, for, while, repeat, try (as a catch block), match                         |
| `elseif`            | conditional statement, also used with `ifdef`                                                            |


# Calling C from Pony

FFI is built into Pony and native libraries may be directly referenced in Pony code. There is no need to code or configure bindings, wrappers or interfaces.


A random integer in [0, 2^64)
"""

fun ref u8(): U8 =>
"""
A random integer in [0, 2^8)
"""
(next() >> 56).u8()

fun ref u16(): U16 =>
"""
A random integer in [0, 2^16)
"""
(next() >> 48).u16()

fun ref u32(): U32 =>
"""
A random integer in [0, 2^32)
"""
(next() >> 32).u32()


end
end
l

fun reverse(): List[this->A!]^ =>
"""
Builds a new `List` by reversing the elements in the `List`.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.reverse() // ["c"; "b"; "a"]
```
"""
try
_reverse(head()?, List[this->A!])
else
List[this->A!]
end

fun _reverse(ln: this->ListNode[A], acc: List[this->A!]): List[this->A!]^ =>


fun box ipproto_pfsync()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_pigp¶
[Source]


fld¶
[Source]
Floored integer division, rounded towards negative infinity.
fun box fld(
y: A)
: A

Parameters¶

y: A

Returns¶

A

mod¶
[Source]
Calculate the modulo after floored integer division, rounded towards negative infinity (fld).


map.pony

1
2
3
4
5
6
7
8
9
10
11


Bool val


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


fun box so_vendor()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_vm_sockets_buffer_min_size¶
[Source]


fun box sctp_maxburst()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_max_burst¶
[Source]


Public Functions¶
has_next¶
[Source]
Returns true if this Iterator is not yet exhausted.
That means that a value returned from a subsequent call to next()
is a valid part of this iterator.
Returns false if this Iterator is exhausted.
The behavior of next() after this function returned false is undefined,
it might throw an error or return values which are not part of this Iterator.
fun ref has_next()
: Bool val

Returns¶

Bool val

next¶
[Source]
Generate the next value.


fun box ip_recvttl()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_router_alert¶
[Source]


"""
try
let notify = _notify as InputNotify
var sum: USize = 0

while true do
let chunk_size = _chunk_size
var data = recover Array[U8] .> undefined(chunk_size) end

let len = @pony_os_stdin_read(data.cpointer(), data.size())

match len
| -1 =>
// Error, possibly would block. Try again.
return true
| 0 =>
// EOF. Close everything, stop reading.
_close_event()
notify.dispose()
_notify = None


: None val

Returns¶

None val

getsockopt¶
[Source]
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
system call's sockopt_len_t * 5th argument.
In case of system call failure, this function returns the 2-tuple:
1. The value of errno.


data: Array[U8 val] val

Returns¶

String val^

from_iso_array¶
[Source]
Create a string from an array, reusing the underlying data pointer
new iso from_iso_array(
data: Array[U8 val] iso)
: String iso^

Parameters¶

data: Array[U8 val] iso

Returns¶


fun fld_partial(y: I16): I16 ? =>
_SignedPartialArithmetic.fld_partial[I16, U16](this, y)?

fun mod_partial(y: I16): I16 ? =>
_SignedPartialArithmetic.mod_partial[I16, U16](this, y)?

primitive I32 is SignedInteger[I32, U32]
new create(value: I32) => value
new from[A: (Number & Real[A] val)](a: A) => a.i32()

new min_value() => -0x8000_0000
new max_value() => 0x7FFF_FFFF

fun abs(): U32 => if this < 0 then (-this).u32() else this.u32() end
fun bit_reverse(): I32 => @"llvm.bitreverse.i32"(this.u32()).i32()
fun bswap(): I32 => @"llvm.bswap.i32"(this.u32()).i32()
fun popcount(): U32 => @"llvm.ctpop.i32"(this.u32())
fun clz(): U32 => @"llvm.ctlz.i32"(this.u32(), false)


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


USize val

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

Returns¶

F32 val

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

Returns¶


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


U32 val

ipv4_addr¶
[Source]
Returns IPV4 address (_addr field in the class) if ip4() is True.
If ip4() is False then the contents are invalid.
fun box ipv4_addr()
: U32 val

Returns¶

U32 val

ipv6_addr¶
[Source]
Returns IPV6 address as the 4-tuple (say a).
a._1 = _addr1 // Bits 0-32 of the IPv6 address in host byte order.


Parameters¶

y: A

Returns¶

A

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

Parameters¶

y: A

Returns¶


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


FormatExp¶
[Source]
primitive val FormatExp is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


fun box tcp_notsent_lowat()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

tcp_pcap_out¶
[Source]


fun box deb_string()
: String val

Returns¶

String val


792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811


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

Parameters¶

n: U32 val = 0

Returns¶

String val

right¶
[Source]
Move the cursor right n columns. 0 is the same as 1.


that: ASCIINUL val

Returns¶

Bool val

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

Parameters¶

that: ASCIINUL val

Returns¶


Process package¶
The Process package provides support for handling Unix style processes.
For each external process that you want to handle, you need to create a
ProcessMonitor and a corresponding ProcessNotify object. Each
ProcessMonitor runs as it own actor and upon receiving data will call its
corresponding ProcessNotify's method.
Example program¶
The following program will spawn an external program and write to it's
STDIN. Output received on STDOUT of the child process is forwarded to the
ProcessNotify client and printed.
use "backpressure"
use "process"
use "files"


ULong val

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

Returns¶

USize val

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

Returns¶


var ponynoscale: Bool = false
"""
Don't scale down the scheduler threads.
See --ponymaxthreads on how to specify the number of threads explicitly.
Can't be used with --ponyminthreads.
"""

var ponysuspendthreshold: U32 = 0
"""
Amount of idle time before a scheduler thread suspends itself to minimize
resource consumption (max 1000 ms, min 1 ms).
Defaults to 1 ms.
"""

var ponycdinterval: U32 = 100
"""
Run cycle detection every N ms (max 1000 ms, min 10 ms).
Defaults to 100 ms.
"""


: Bool val

Parameters¶

flags: U32 val

Returns¶

Bool val

writeable¶
[Source]
Returns true if the flags contain the writeable flag.
fun box writeable(
flags: U32 val)
: Bool val

Parameters¶


`as` can also be used to get a more specific type of an object from an alias to it that is an interface or a trait. Let's say, for example, that you have a library for doing things with furry, rodent-like creatures. It provides a `Critter` interface which programmers can then use to create specific types of critters.

```pony
interface Critter
fun wash(): String
```

The programmer uses this library to create a `Wombat` and a `Capybara` class. But the `Capybara` class provides a new method, `swim()`, that is not part of the `Critter` class. The programmer wants to store all of the critters in an array, in order to carry out actions on groups of critters. Now assume that when capybaras finish washing they want to go for a swim. The programmer can accomplish that by using `as` to attempt to use each `Critter` object in the `Array[Critter]` as a `Capybara`. If this fails because the `Critter` is not a `Capybara`, then an error is raised; the program can swallow this error and go on to the next item.

```pony
interface Critter
fun wash(): String

class Wombat is Critter
fun wash(): String => "I'm a clean wombat!"

class Capybara is Critter
fun wash(): String => "I feel squeaky clean!"
fun swim(): String => "I'm swimming like a fish!"


552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571


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

Returns¶

MinHeapPriority[A] val^

Public Functions¶
apply¶
[Source]
fun box apply(
x: A,
y: A)
: Bool val

Parameters¶

x: A
y: A


(size() < that.size()) and (this <= that)

fun le(that: HashSet[A, H] box): Bool =>
"""
Returns true if every element in this is also in that.
"""
try
for value in values() do
that(value)?
end
true
else
false
end

fun gt(that: HashSet[A, H] box): Bool =>
"""
Returns true if every element in that is also in this, and this has more
elements than that.
"""


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

Returns¶

U32 val

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

Parameters¶


U128 val

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

Returns¶

ULong val

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

Returns¶


class CommutativeMultiplicationProperty is IntPairProperty
fun name(): String => "commutativity/mul"

fun int_property[T: (Int & Integer[T] val)](x: T, y: T, h: PropertyHelper)? =>
h.assert_eq[T](x * y, y * x)
```
"""
fun gen(): Generator[IntPairPropertySample] =>
Generators.map3[U8, U128, U128, IntPairPropertySample](
Generators.u8(),
Generators.u128(),
Generators.u128(),
{(choice, int1, int2) => IntPairPropertySample(choice, int1, int2) })

fun ref property(sample: IntPairPropertySample, h: PropertyHelper) ? =>
let x = sample.int1
let y = sample.int2
match sample.choice % 14
| 0 => int_property[U8](x.u8(), y.u8(), h)?
| 1 => int_property[U16](x.u16(), y.u16(), h)?


returns `Promise[B]`.

Why is `flatten_next` valuable given that next could take a `B` that is of
a type like `Promise[String]`? Let's start with some code to demonstrate the
problem that arises when returning `Promise[Promise[B]]` from `next`.

Let's say we have a library for accessing the GitHub REST API:

```pony
class GitHub
new create(personal_access_token: String)

fun get_repo(repo: String): Promise[Repository]

class Repository
fun get_issue(number: I64): Promise[Issue]

class Issue
fun title(): String
```


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


fun so_vm_sockets_peer_host_vm_id():I32 => @pony_os_sockopt_option(I32(922))
fun so_vm_sockets_trusted():I32 => @pony_os_sockopt_option(I32(923))
fun so_wantmore():I32 => @pony_os_sockopt_option(I32(924))
fun so_wantoobflag():I32 => @pony_os_sockopt_option(I32(925))
fun so_wifi_status():I32 => @pony_os_sockopt_option(I32(926))
fun tcp6_mss():I32 => @pony_os_sockopt_option(I32(927))
fun tcpci_flag_lossrecovery():I32 => @pony_os_sockopt_option(I32(928))
fun tcpci_flag_reordering_detected():I32 => @pony_os_sockopt_option(I32(929))
fun tcpci_opt_ecn():I32 => @pony_os_sockopt_option(I32(930))
fun tcpci_opt_sack():I32 => @pony_os_sockopt_option(I32(931))
fun tcpci_opt_timestamps():I32 => @pony_os_sockopt_option(I32(932))
fun tcpci_opt_wscale():I32 => @pony_os_sockopt_option(I32(933))
fun tcpf_ca_cwr():I32 => @pony_os_sockopt_option(I32(934))
fun tcpf_ca_disorder():I32 => @pony_os_sockopt_option(I32(935))
fun tcpf_ca_loss():I32 => @pony_os_sockopt_option(I32(936))
fun tcpf_ca_open():I32 => @pony_os_sockopt_option(I32(937))
fun tcpf_ca_recovery():I32 => @pony_os_sockopt_option(I32(938))
fun tcpi_opt_ecn():I32 => @pony_os_sockopt_option(I32(939))
fun tcpi_opt_ecn_seen():I32 => @pony_os_sockopt_option(I32(940))
fun tcpi_opt_sack():I32 => @pony_os_sockopt_option(I32(941))


## Shared mutable data is hard

The problem with concurrency is shared mutable data. If two different threads have access to the same piece of data then they might try to update it at the same time. At best this can lead to the two threads having different versions of the data. At worst the updates can interact badly resulting in the data being overwritten with garbage. The standard way to avoid these problems is to use locks to prevent data updates from happening at the same time. This causes big performance hits and is very difficult to get right, so it causes lots of bugs.


U32 val

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

Returns¶

U64 val

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

Returns¶


fun box sctp_get_assoc_id_list()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_get_local_addresses¶
[Source]


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


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


OSSockOpt¶
[Source]
Convenience functions to fetch the option level and option
name constants (arguments #2 and #3) for the
getsockopt(2) and setsockopt(2) operating system calls.
The values of the option level and option name constants are
typically C preprocessor macros, e.g., #define SOMETHING 42.
These macro names are upper case and may contain multiple
consecutive underscore characters (though this is rare, for
example, IP_NAT__XXX).  The function names in this primitive
are derived by the C macro name and then:

converted to lower case


fun u128(): U128 =>
if this > U128.max_value().f64() then
return U128.max_value()
elseif this < U128.min_value().f64() then
return U128.min_value()
end

let bit = bits()
let high = (bit >> 32).u32()
let ex = ((high and 0x7FF00000) >> 20) - 1023

if (ex < 0) or ((high and 0x80000000) != 0) then
return 0
end

var r = ((bit and 0x000FFFFFFFFFFFFF) or 0x0010000000000000).u128()
let ex' = ex.u128()

if ex' > 52 then


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

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

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

var any_exec: Bool val¶
[Source]
`true if every user can execute the file.

Public Functions¶
exec¶
[Source]
Set the executable flag for everyone.


892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911


10
8
6
4
2

If dec is 0, produces an infinite series of max.
If dec is negative, produces a range with max as the only value.
class ref 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))] is
Iterator[A] ref

Implements¶

Iterator[A] ref


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

Returns¶

I128 val

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

Returns¶

ILong val


Second BOOM!
Third BOOM!
The size of our first partitioned list (matches predicate): 1
The size of our second partitioned list (doesn't match predicate): 1
Our matching partition elements are:
Second BOOM!

use "collections"

actor Main
new create(env:Env) =>

// Create a new empty List of type String
let my_list = List[String]()

env.out.print("A new empty list has " + my_list.size().string() + " nodes.") // 0

// Push a String literal onto our empty List
my_list.push("A single String")
env.out.print("Adding one node to our empty list means it now has a size of "


None val

complete_action¶
[Source]
MUST be called for each action expectation that was set up in a long test
to fulfill the expectations. Any expectations that are still outstanding
when the long test timeout runs out will be printed by name when it fails.
Completing all outstanding actions is enough to finish the test. There's no
need to also call the complete method when the actions are finished.
Calling the complete method will finish the test immediately, without
waiting for any outstanding actions to be completed.
fun box complete_action(
name: String val)
: None val

Parameters¶

name: String val


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

Parameters¶

y: ILong val

Returns¶

Bool val

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


Returns¶

USize val

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

Returns¶

U64 val

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


fun box sctp_recvnxtinfo()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_recv_rwnd_logging_enable¶
[Source]


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


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


# Integration into PonyTest

There are two ways of integrating a [Property](pony_check-Property1.md) into
[PonyTest](pony_test--index.md):

1. In order to pass your Property to the PonyTest engine, you need to wrap it
inside a [Property1UnitTest](pony_check-Property1UnitTest.md).

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

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

2. Run as many [Properties](pony_check-Property1.md) as you wish inside one
PonyTest [UnitTest](pony_test-UnitTest.md) using the convenience function
[PonyCheck.for_all](pony_check-PonyCheck.md#for_all) providing a
[Generator](pony_check-Generator), the [TestHelper](pony_test-TestHelper.md)


292
293
294
295
296class Writer
"""
A buffer for building messages.

`Writer` provides an way to create byte sequences using common
data encodings. The `Writer` manages the underlying arrays and
sizes. It is useful for encoding data to send over a network or
store in a file. Once a message has been built you can call `done()`
to get the message's `ByteSeq`s, and you can then reuse the
`Writer` for creating a new message.

For example, suppose we have a TCP-based network data protocol where
messages consist of the following:

* `message_length` - the number of bytes in the message as a
big-endian 32-bit integer


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


Parameters¶

y: A

Returns¶

A

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

Returns¶

A


=>
"""
Determine the base of an integer starting at the specified index.
If a non-0 base is given use that. If given base is 0 read the base
specifying prefix, if any, to detect base 2 or 16.
If no base is specified and no prefix is found default to decimal.
Note that a leading 0 does NOT imply octal.
Report the base found and the number of single-byte characters in
the prefix.
"""
if base > 0 then
return (A(0).from[U8](base), 0)
end

// Determine base from prefix
if (index + 2) >= _size then
// Not enough characters, must be decimal
return (10, 0)
end


next_path: String val

Returns¶

String val

clean¶
[Source]
Replace multiple separators with a single separator.
Convert / to the OS separator.
Remove instances of . from the path.
Remove instances of .. and the preceding path element from the path.
The result will have no trailing slash unless it is a root directory.
If the result would be empty, "." will be returned instead.
fun box clean(
path: String val)
: String val

Parameters¶


Generator[T] box ?

zip2[T1: T1, T2: T2]¶
[Source]
Zip two generators into a generator of a 2-tuple
containing the values generated by both generators.
fun box zip2[T1: T1, T2: T2](
gen1: Generator[T1] box,
gen2: Generator[T2] box)
: Generator[(T1 , T2)] box

Parameters¶

gen1: Generator[T1] box
gen2: Generator[T2] box

Returns¶


Returns¶

TCPConnectionNotify iso^ ?


end)

fun ref step_by(n: USize = 1): Iter[A!] =>
"""
Return an iterator that yields every `n`th element of the
original iterator. n == 0 is treated like n == 1 rather than an error.


42
fun ref next_or(
default: A)
: A

Parameters¶

default: A

Returns¶

A

map_stateful[B: B]¶
[Source]
Allows stateful transformation of each element from the iterator, similar
to map.
fun ref map_stateful[B: B](


Mirrors the [TestHelper](pony_test-TestHelper.md) API as closely as possible.

Contains assertion functions and functions for completing asynchronous
properties, for expecting and completing or failing actions.

Internally a new PropertyHelper will be created for each call to
a property with a new sample and also for every shrink run.
So don't assume anything about the identity of the PropertyHelper inside of
your Properties.

This class is `val` by default so it can be safely passed around to other
actors.

It exposes the process [Env](builtin-Env.md) as public `env` field in order to
give access to the root authority and other stuff.
"""
let _runner: _IPropertyRunner
let _run_notify: _PropertyRunNotify
let _run: _Round


### Example

```pony
Iter[String](["alpha"; "beta"; "gamma"])
.flat_map[U8]({(s: String): Iterator[U8] => s.values() })
```
`a l p h a b e t a g a m m a`
"""
Iter[B](
object is Iterator[B]
var _iterb: Iterator[B] =
try f(_iter.next()?)? else _EmptyIter[B] end

fun ref has_next(): Bool =>
if _iterb.has_next() then true
else
if _iter.has_next() then
try
_iterb = f(_iter.next()?)?
has_next()


unshift¶
[Source]
Add an element to the beginning of the array.
fun ref unshift(
value: A)
: None val

Parameters¶

value: A

Returns¶

None val

shift¶
[Source]
Remove an element from the beginning of the array.


y: I32 val

Returns¶

Bool val

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

Returns¶

USize val

hash64¶
[Source]


that: Generators val)
: Bool val

Parameters¶

that: Generators val

Returns¶

Bool val

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

Parameters¶


y: USize val

Returns¶

Bool val

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

Returns¶

USize val

hash64¶
[Source]


Parameters¶

that: (Less val | Equal val | Greater val)

Returns¶

Bool val


Vec[A: Any #share]¶
[Source]
A persistent vector based on the Hash Array Mapped Trie from 'Ideal Hash
Trees' by Phil Bagwell.
class val Vec[A: Any #share]

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

Returns¶


be writev(data: ByteSeqIter) =>
"""
Write an iterable collection of ByteSeqs.
"""
for bytes in data.values() do
_write_final(bytes)
end

be done_writing() =>
"""
Set the _done_writing flag to true. If _pending is empty we can close the
_stdin pipe.
"""
_done_writing = true
Backpressure.release(_backpressure_auth)
if _pending.size() == 0 then
_stdin.close_near()
end


Iterator[String iso^] ref

Constructors¶
create¶
[Source]
Create a FileLines instance on a given file.
This instance returns lines from the position of the given file
at the time this constructor is called. Later manipulation of the file position
is not accounted for. As a result iterating with this class will always return the full
file content without gaps or repeated lines.
min_read_size determines the minimum amount of bytes to read from the file
in one go. This class keeps track of the line lengths in the current file
and uses the length of the last line as amount of bytes to read next, but it
will never read less than min_read_size.
new ref create(
file: File ref,
min_read_size: USize val = 256)
: FileLines ref^


92
93
94
95
96
97
98
99
100
101
102
103
104use @pony_os_stdin_setup[Bool]()
use @pony_os_stdout_setup[None]()

class val Env
"""
An environment holds the command line and other values injected into the
program by default by the runtime.
"""


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


Returns¶

I8 val

i16¶
[Source]
A random integer in [-2^15, 2^15)
fun ref i16()
: I16 val

Returns¶

I16 val

i32¶
[Source]
A random integer in [-2^31, 2^31)


# Pass an Array of values to FFI

```pony
use @eglChooseConfig[U32](disp: Pointer[_EGLDisplayHandle], attrs: Pointer[U16] tag,
config: Pointer[_EGLConfigHandle], config_size: U32, num_config: Pointer[U32])

primitive _EGLConfigHandle
let a = Array[U16](8)
a.push(0x3040)
a.push(0x4)
a.push(0x3033)
a.push(0x4)
a.push(0x3022)
a.push(0x8)
a.push(0x3023)
a.push(0x8)
a.push(0x3024)
let config = Pointer[_EGLConfigHandle]
if @eglChooseConfig(e_dpy, a.cpointer(), config, U32(1), Pointer[U32]) == 0 then
env.out.print("eglChooseConfig failed")


fun box u8()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32¶
[Source]


ASCIINonPrintable¶
[Source]
primitive val ASCIINonPrintable

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

Returns¶

ASCIINonPrintable val^


An empty string. Enough space for len bytes is reserved.
"""
_size = 0
_alloc = len.min(len.max_value() - 1) + 1
_ptr = Pointer[U8]._alloc(_alloc)
_set(0, 0)

new val from_array(data: Array[U8] val) =>
"""
Create a string from an array, reusing the underlying data pointer.
"""
_size = data.size()
_alloc = data.space()
_ptr = data.cpointer()._unsafe()

new iso from_iso_array(data: Array[U8] iso) =>
"""
Create a string from an array, reusing the underlying data pointer
"""
_size = data.size()


fun box netlink_listen_all_nsid()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

netlink_netfilter¶
[Source]


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

Parameters¶

y: U128 val

Returns¶

U128 val

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

Parameters¶


1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031


# Testing with `PonyCheck`

PonyCheck is Pony's property based testing framework. It is designed to work seamlessly with [PonyTest](ponytest.md), Pony's unit testing framework. How is property based testing different than unit testing? Why does Pony include both?

In traditional unit testing, it is the duty and burden of the developer to provide and craft meaningful input examples for the unit under test (be it a class, a function or whatever) and check if some output conditions hold. This is a tedious and error-prone activity.

Property based testing leaves generation of test input samples to the testing engine which generates random examples taken from a description how to do so, so called `Generators`. The developer needs to define a `Generator` and describe the condition that should hold for each and every input sample.

Property based testing first came up as [`QuickCheck`](http://www.cse.chalmers.se/~rjmh/QuickCheck/) in Haskell. It has the nice property of automatically inferring `Generators` from the type of the property parameter, the test input sample.

PonyCheck is heavily inspired by QuickCheck and other great property based testing libraries, namely:

* [Hypothesis](https://github.com/HypothesisWorks/hypothesis-python)
* [Theft](https://github.com/silentbicycle/theft)
* [ScalaCheck](https://www.scalacheck.org/)


fun box ipproto_igrp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_inlsp¶
[Source]


xorshift.pony

1
2
3
4
5
6
7
8
9
10
11