value_iter¶
[Source]
fun box value_iter(
rnd: Randomness ref)
: Iterator[T^] ref

Parameters¶

rnd: Randomness ref

Returns¶

Iterator[T^] ref

value_and_shrink_iter¶
[Source]
fun box value_and_shrink_iter(
rnd: Randomness ref)
: Iterator[(T^ , Iterator[T^] ref)] ref


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


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


Constructors¶
create¶
[Source]
new ref create(
max: A,
min: A,
dec: A = 1)
: Reverse[A] ref^

Parameters¶

max: A
min: A
dec: A = 1

Returns¶

Reverse[A] ref^


fun box so_security_encryption_network()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_select_err_queue¶
[Source]


fun box ip_portrange()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_portrange_high¶
[Source]


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

Returns¶

I128 val

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

Returns¶

ILong val


fun box sctp_listen()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_lock_logging_enable¶
[Source]


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

Parameters¶

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


(let q, let r) = divrem(y)
r
end

fun mul_unsafe(y: I128): I128 =>
"""
Unsafe operation.
If the operation overflows, the result is undefined.
"""
ifdef native128 then
this *~ y
else
this * y
end

fun divrem_unsafe(y: I128): (I128, I128) =>
"""
Unsafe operation.
If y is 0, the result is undefined.
If the operation overflows, the result is undefined.


HashFunction[A] val^

Public Functions¶
hash¶
[Source]
Calculate the hash of some type. This is an alias of the type parameter to
allow data structures to hash things without consuming them.
fun box hash(
x: box->A!)
: USize val

Parameters¶

x: box->A!

Returns¶

USize val


u8_unsafe¶
fun box u8_unsafe()
: U8 val

Returns¶

U8 val

u16_unsafe¶
fun box u16_unsafe()
: U16 val

Returns¶

U16 val


end
end

fun out(msg: Stringable = "") =>
"""
If platform is debug configured, print message to standard output
"""
_print(msg.string(), DebugOut)

fun err(msg: Stringable = "") =>
"""
If platform is debug configured, print message to standard error
"""
_print(msg.string(), DebugErr)

fun _print(msg: String, stream: DebugStream) =>
ifdef debug then
@fprintf(_stream(stream), "%s\n".cstring(), msg.cstring())
end


auth.pony

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


fun ref right(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
"""
Move right.
"""
try
if _cur_pos < _edit.size().isize() then
_cur_pos = _cur_pos + 1
end

while
(_cur_pos < _edit.size().isize()) and
((_edit.at_offset(_cur_pos)? and 0xC0) == 0x80)
do
_cur_pos = _cur_pos + 1
end

_refresh_line()
end


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


spec': CommandSpec box

Returns¶

CommandParser box^

Public Functions¶
parse¶
[Source]
Parses all of the command line tokens and env vars and returns a Command,
or the first SyntaxError.
fun box parse(
argv: Array[String val] box,
envs: (Array[String val] box | None val) = reference)
: (Command box | CommandHelp box | SyntaxError val)

Parameters¶


fun box ilong_unsafe()
: ILong val

Returns¶

ILong val

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

Returns¶

ISize val

u8_unsafe¶
[Source]


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


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


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]


y: A

Returns¶

(A , A)

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

Parameters¶

y: A

Returns¶


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

Parameters¶

value: U128 val

Returns¶

U128 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 |


return (consume this, consume b)
end

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

fun ref copy_from[B: (A & Real[B] val & U8) = A](
src: Array[U8] box,
src_idx: USize,
dst_idx: USize,
len: USize)
=>
"""


USize val

reserve¶
[Source]
Reserve space for len elements, including whatever elements are already in
the array. Array space grows geometrically.
fun ref reserve(
len: USize val)
: None val

Parameters¶

len: USize val

Returns¶

None val


: U32 val

Returns¶

U32 val

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

Returns¶

U64 val

u128¶
[Source]
fun ref u128()


Parameters¶

wall: (I64 val , I64 val)

Returns¶

U64 val

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

Parameters¶

that: Nanos val


ISize val ?

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

Parameters¶

y: ISize val

Returns¶

(ISize val , ISize val) ?

fld_partial¶


CreateFile val^

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

Parameters¶

from: FilePath val

Returns¶

(File ref | FileOK val | FileError val |


132
133
134
135
136
137
138
139
140
141
142
143
144type MinHeap[A: Comparable[A] #read] is BinaryHeap[A, MinHeapPriority[A]]
type MaxHeap[A: Comparable[A] #read] is BinaryHeap[A, MaxHeapPriority[A]]

class BinaryHeap[A: Comparable[A] #read, P: BinaryHeapPriority[A]]
"""
A priority queue implemented as a binary heap. The `BinaryHeapPriority` type
parameter determines whether this is max-heap or a min-heap.
"""


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


Parameters¶

base: U8 val = 0

Returns¶

U128 val ?

ulong¶
[Source]
fun box ulong(
base: U8 val = 0)
: ULong val ?

Parameters¶

base: U8 val = 0


+ " (after "
+ shrink_rounds.string()
+ " shrinks)"
)

fun _report_failed(sample_repr: String,
shrink_rounds: USize = 0,
loc: SourceLoc = __loc) =>
"""
Report a failed property and signal failure to the `PropertyResultNotify`.
"""
_notify.fail(
"Property failed for sample "
+ sample_repr
+ " (after "
+ shrink_rounds.string()
+ " shrinks)"
)


fun box so_l2cap_oflow()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_label¶
[Source]


1 << (if x == 0 then 0 else bitwidth() - x end)

fun abs(): U64 => this
fun bit_reverse(): U64 => @"llvm.bitreverse.i64"(this)
fun bswap(): U64 => @"llvm.bswap.i64"(this)
fun popcount(): U64 => @"llvm.ctpop.i64"(this)
fun clz(): U64 => @"llvm.ctlz.i64"(this, false)
fun ctz(): U64 => @"llvm.cttz.i64"(this, false)

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

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


ULong val

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

Returns¶

ULong val

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

Returns¶


I16 val

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

Parameters¶

y: I16 val

Returns¶

I16 val

mod¶
[Source]


(U64 val , Bool val)

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

Parameters¶

y: U64 val

Returns¶

(U64 val , Bool val)

mulc¶
[Source]


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

Returns¶

ULong val

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

Returns¶

USize val


# Aggregation

Often it is desirable to run a collection of unit tests from multiple different
source files. For example, if several packages within a bundle each have their
own unit tests it may be useful to run all tests for the bundle together.

This can be achieved by writing an aggregate test list class, which calls the
list function for each package. The following is an example that aggregates the
tests from packages `foo` and `bar`.

```pony
use "pony_test"
use bar = "bar"
use foo = "foo"

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

new make() =>


Returns¶

I8 val ?

u16_be¶
[Source]
Get a big-endian U16.
fun ref u16_be()
: U16 val ?

Returns¶

U16 val ?

u16_le¶
[Source]
Get a little-endian U16.
fun ref u16_le()


that: FileRemove val

Returns¶

Bool val

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

Parameters¶

that: FileRemove val

Returns¶


I64 val

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

Parameters¶

y: I64 val

Returns¶

I64 val

mod¶
[Source]


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


tcp_listener.pony

1
2
3
4
5
6
7
8
9
10
11


HashFunction[A: A]¶
[Source]
A pluggable hash function.
interface val HashFunction[A: A]

Constructors¶
create¶
[Source]
Data structures create instances internally. Use a primitive if possible.
new val create()
: HashFunction[A] val^

Returns¶


"""
min + u64(0, (max - min).u64()).i64()

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

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

fun ref ilong(
min: ILong = ILong.min_value(),


Parameters¶

y: box->A

Returns¶

Bool val

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

Parameters¶


Use the structural equality function from the type parameter.
"""
x == y

primitive HashEq64[A: (Hashable64 #read & Equatable[A] #read)] is
HashFunction64[A]
fun hash64(x: box->A): U64 =>
"""
Use the hash function from the type parameter.
"""
x.hash64()

fun eq(x: box->A, y: box->A): Bool =>
"""
Use the structural equality function from the type parameter.
"""
x == y

primitive HashIs[A] is (HashFunction[A] & HashFunction64[A])
fun hash(x: box->A!): USize =>


next().ulong()
end

fun ref usize(): USize =>
"""
A random integer in [0, USize.max_value()]
"""
ifdef ilp32 then
(next() >> 32).usize()
else
next().usize()
end

fun ref i8(): I8 =>
"""
A random integer in [-2^7, 2^7)
"""
u8().i8()

fun ref i16(): I16 =>


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


fun box ipproto_larp()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipproto_leaf2¶
[Source]


# Use names

As we saw above the use command adds all the public types from a package into the namespace of the using file. This means that using a package may define type names that you want to use for your own types. Furthermore, if you use two packages within a file they may both define the same type name, causing a clash in your namespace. For example:

```pony
// In package A
class Foo

// In package B
class Foo

// In your code
use "packageA"
use "packageB"

class Bar
var _x: Foo
```

The declarations of _x is an error because we don't know which `Foo` is being referred to. Actually using 'Foo' is not even required, simply using both `packageA` and `packageB` is enough to cause an error here.


MapPairs[K: K, V: V, H: HashFunction[K] val, M: HashMap[K, V, H] #read]¶
[Source]
An iterator over the keys and values in a map.
class ref MapPairs[K: K, V: V, H: HashFunction[K] val, M: HashMap[K, V, H] #read] is
Iterator[(M->K , M->V)] ref

Implements¶

Iterator[(M->K , M->V)] ref

Constructors¶
create¶


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


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


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


gen': Generator[T] val
testHelper: TestHelper val

Returns¶

ForAll[T] ref^

Public Functions¶
apply¶
[Source]
execute
fun ref apply(
prop: {(T, PropertyHelper) ?}[T] val)
: None val ?

Parameters¶

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


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


Bool val

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

Parameters¶

y: I128 val

Returns¶

Bool val

le¶
[Source]


FormatOctalBare¶
[Source]
primitive val FormatOctalBare is
FormatSpec val

Implements¶

FormatSpec val

Constructors¶
create¶
[Source]


var _count: USize = 0
var _paused: Bool = false
let _read_buffer_size: USize
let _yield_after_reading: USize
let _yield_after_writing: USize

new create(
auth: TCPListenAuth,
notify: TCPListenNotify iso,
host: String = "",
service: String = "0",
limit: USize = 0,
read_buffer_size: USize = 16384,
yield_after_reading: USize = 16384,
yield_after_writing: USize = 16384)
=>
"""
Listens for both IPv4 and IPv6 connections.
"""
_limit = limit


fun box dccp_sockopt_ccid_tx_info()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

dccp_sockopt_change_r¶
[Source]


String iso^

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

Returns¶

I8 val

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

Returns¶


ourself a resume message and stop reading, to avoid starving other actors.
Currently we can handle a varying value of _expect (greater than 0) and
constant _expect of 0 but we cannot handle switching between these two
cases.
"""
ifdef not windows then
try
var sum: USize = 0
var received_called: USize = 0
_reading = true

while _readable and not _shutdown_peer do
// exit if muted
if _muted then
_reading = false
return
end

// distribute the data we've already read that is in the `read_buf`
// and able to be distributed


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


None

fun ref closed() =>
None


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


fun box sctp_get_remote_addr_size()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_get_stat_log¶
[Source]


## Divide by zero on floating points

In conformance with IEEE 754, *floating point division by zero results in `inf` or `-inf`*, depending on the sign of the numerator.

If you can assert that your denominator cannot be `0`, it is possible to use [Unsafe Division](/expressions/arithmetic.md#floating-point) to gain some performance:

```pony
let x = F64(1.5) /~ F64(0.5)
```


ILong val

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

Parameters¶

y: ILong val

Returns¶

ILong val

sub¶


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

Parameters¶

y: box->A

Returns¶

Bool val

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

Parameters¶


(U32 val , Bool val)

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

Parameters¶

y: U32 val

Returns¶

U32 val ?

fld_unsafe¶
[Source]


Get the i-th element, raising an error if the index is out of bounds.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.apply(1)? end // "b"
```
"""
index(i)?()?

fun ref update(i: USize, value: A): A^ ? =>
"""
Change the i-th element, raising an error if the index is out of bounds, and
returning the previous value.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.update(1, "z")? end // Returns "b" and List now contains ["a"; "z"; "c"]
```
"""
index(i)?()? = consume value


ULong val

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

Returns¶

ULong val

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

Returns¶


: N

Parameters¶

n: N

Returns¶

N

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

Parameters¶


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


fun box ipctl_rtmaxcache()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipctl_sendredirects¶
[Source]


error
end
end)

fun ref take_while(f: {(A!): Bool ?} box): Iter[A!]^ =>
"""
Return an iterator that returns values while the predicate `f` returns
true. This iterator short-circuits the first time that `f` returns false or
raises an error.


hard_close()
end
end
end

false

fun ref _manage_pending_buffer(
bytes_sent: USize,
bytes_to_send: USize,
num_to_send: USize)
: Bool ?
=>
"""
Manage pending buffer for data sent. Returns a boolean of whether
the pending buffer is empty or not.
"""
var len = bytes_sent
if len < bytes_to_send then
var num_sent: USize = 0


y: I8 val

Returns¶

I8 val ?

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

Parameters¶

y: I8 val

Returns¶


fun box icmp_parameterprob()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

icmp_port_unreach¶
[Source]


IntPropertySample¶
[Source]
class ref IntPropertySample is
Stringable box

Implements¶

Stringable box

Constructors¶
create¶
[Source]


# Constraints


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


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

Implements¶

UnsignedInteger[U32 val] val

Constructors¶
create¶
[Source]


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


that: Pointer[A] tag

Returns¶

Bool val

ge¶
[Source]
fun tag ge(
that: Pointer[A] tag)
: Bool val

Parameters¶

that: Pointer[A] tag

Returns¶

Bool val


Arg¶
[Source]
Arg contains a spec and an effective value for a given arg.
class val Arg

Constructors¶
create¶
[Source]
new val create(
spec': ArgSpec val,
value': (Bool val | String val | I64 val |
U64 val | F64 val | _StringSeq val))
: Arg val^


: ILong val

Returns¶

ILong val

isize¶
fun box isize()
: ISize val

Returns¶

ISize val

u8¶
fun box u8()
: U8 val


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48interface ANSINotify
"""
Receive input from an ANSITerm.
"""


fun ipproto_routing():I32 => @pony_os_sockopt_level(I32(4091))
fun ipproto_rsvp():I32 => @pony_os_sockopt_level(I32(4092))
fun ipproto_rvd():I32 => @pony_os_sockopt_level(I32(4093))
fun ipproto_satexpak():I32 => @pony_os_sockopt_level(I32(4094))
fun ipproto_satmon():I32 => @pony_os_sockopt_level(I32(4095))
fun ipproto_sccsp():I32 => @pony_os_sockopt_level(I32(4096))
fun ipproto_sctp():I32 => @pony_os_sockopt_level(I32(4097))
fun ipproto_sdrp():I32 => @pony_os_sockopt_level(I32(4098))
fun ipproto_send():I32 => @pony_os_sockopt_level(I32(4099))
fun ipproto_sep():I32 => @pony_os_sockopt_level(I32(4100))
fun ipproto_shim6():I32 => @pony_os_sockopt_level(I32(4101))
fun ipproto_skip():I32 => @pony_os_sockopt_level(I32(4102))
fun ipproto_spacer():I32 => @pony_os_sockopt_level(I32(4103))
fun ipproto_srpc():I32 => @pony_os_sockopt_level(I32(4104))
fun ipproto_st():I32 => @pony_os_sockopt_level(I32(4105))
fun ipproto_svmtp():I32 => @pony_os_sockopt_level(I32(4106))
fun ipproto_swipe():I32 => @pony_os_sockopt_level(I32(4107))
fun ipproto_tcf():I32 => @pony_os_sockopt_level(I32(4108))
fun ipproto_tcp():I32 => @pony_os_sockopt_level(I32(4109))
fun ipproto_tlsp():I32 => @pony_os_sockopt_level(I32(4110))


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


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


end
| (let errno: U32, _) =>
// System call failed
end
```
"""
_OSSocket.getsockopt(_fd, level, option_name, option_max_size)

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

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`.


test_helper.pony

1
2
3
4
5
6
7
8
9
10
11


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


Bool val

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

Returns¶

Bool val

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

Returns¶


Parameters¶

offset: USize val = 0

Returns¶

U16 val ?

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

Parameters¶

offset: USize val = 0


fun box ipv6_recvhopopts()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_recvpathmtu¶
[Source]


fun box ipctl_maxid()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipctl_rtmaxcache¶
[Source]


Bool val

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

Parameters¶

that: UDPAuth val

Returns¶

Bool val


: String val

Returns¶

String val

exclusion_group¶
[Source]
Report the test exclusion group, returning an empty string for none.
The default body returns an empty string.
fun box exclusion_group()
: String val

Returns¶

String val

apply¶


# Long running behaviors

Another way to monopolize a scheduler thread is to write a behavior that never exits or takes a really long time to exit.

```pony
be bad_citizen() =>
while true do
_env.out.print("Never gonna give you up. Really gonna make you cry")
end
```

That is some seriously bad citizen code that will hog a scheduler thread forever. Call that behavior a few times and your program will grind to a halt. If you find yourself writing code with loops that will run for a long time, stop and rethink your design. Take a look at the [Timer](https://stdlib.ponylang.io/time-Timer/) class from the standard library. Combine that together with a counter in your class and you can execute the same behavior repeatedly while yielding your scheduler thread to other actors.


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


U32 val

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

Returns¶

U64 val

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

Returns¶


Parameters¶

predicate: Bool val
msg: String val = ""
loc: SourceLoc val = __loc

Returns¶

Bool val

assert_error¶
[Source]
Assert that the given test function throws an error when run.
fun box assert_error(
test: {(): None ?} box,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val


embed _ip: NetAddress = NetAddress

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


new val create()
: FormatGeneral val^

Returns¶

FormatGeneral val^

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

Parameters¶

that: FormatGeneral val

Returns¶


# Recovering Capabilities

A `recover` expression lets you "lift" the reference capability of the result. A mutable reference capability (`iso`, `trn`, or `ref`) can become _any_ reference capability, and an immutable reference capability (`val` or `box`) can become any immutable or opaque reference capability.


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


52
53
54type AsioEventID is Pointer[AsioEvent] tag

trait tag AsioEventNotify
be _event_notify(event: AsioEventID, flags: U32, arg: U32)

primitive AsioEvent
"""
Functions for asynchronous event notification.
"""
fun none(): AsioEventID =>
"""
An empty event.
"""
AsioEventID

fun readable(flags: U32): Bool =>
"""
Returns true if the flags contain the readable flag.


None val

set_up¶
fun ref set_up(
h: TestHelper val)
: None val ?

Parameters¶

h: TestHelper val

Returns¶

None val ?

tear_down¶
fun ref tear_down(


fun box ipv6_2292rthdr()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_addr_preferences¶
[Source]


Capsicum package¶
Access to Capsicum capabilities for UNIX systems -- primarily in use by BSD-based systems.
Public Types¶

primitive Cap
type CapRights
class CapRights0


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

Parameters¶

y: A

Returns¶

A


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28class SplitMix64 is Random
"""
Very fast Pseudo-Random-Number-Generator
using only 64 bit of state, as detailed at:


fun box sctp_cwnd_logging_enable()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_cwr_in_same_window¶
[Source]


fun box u8_unsafe()
: U8 val

Returns¶

U8 val

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

Returns¶

U16 val

u32_unsafe¶
[Source]


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


fun sctp_authentication():I32 => @pony_os_sockopt_option(I32(522))
fun sctp_auth_active_key():I32 => @pony_os_sockopt_option(I32(523))
fun sctp_auth_chunk():I32 => @pony_os_sockopt_option(I32(524))
fun sctp_auth_deactivate_key():I32 => @pony_os_sockopt_option(I32(525))
fun sctp_auth_delete_key():I32 => @pony_os_sockopt_option(I32(526))
fun sctp_auth_key():I32 => @pony_os_sockopt_option(I32(527))
fun sctp_auth_supported():I32 => @pony_os_sockopt_option(I32(528))
fun sctp_autoclose():I32 => @pony_os_sockopt_option(I32(529))
fun sctp_auto_asconf():I32 => @pony_os_sockopt_option(I32(530))
fun sctp_badcrc():I32 => @pony_os_sockopt_option(I32(531))
fun sctp_bindx_add_addr():I32 => @pony_os_sockopt_option(I32(532))
fun sctp_bindx_rem_addr():I32 => @pony_os_sockopt_option(I32(533))
fun sctp_blk_logging_enable():I32 => @pony_os_sockopt_option(I32(534))
fun sctp_bound():I32 => @pony_os_sockopt_option(I32(535))
fun sctp_cause_cookie_in_shutdown():I32 => @pony_os_sockopt_option(I32(536))
fun sctp_cause_deleting_last_addr():I32 => @pony_os_sockopt_option(I32(537))
fun sctp_cause_deleting_src_addr():I32 => @pony_os_sockopt_option(I32(538))
fun sctp_cause_illegal_asconf_ack():I32 => @pony_os_sockopt_option(I32(539))
fun sctp_cause_invalid_param():I32 => @pony_os_sockopt_option(I32(540))
fun sctp_cause_invalid_stream():I32 => @pony_os_sockopt_option(I32(541))


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


Parameters¶

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

Returns¶

None val ?


fun box msg_notification()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ndrvproto_ndrv¶
[Source]


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


@"llvm.bswap.i64"(this.u64()).ulong()
end

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

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

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


I16¶
[Source]
primitive val I16 is
SignedInteger[I16 val, U16 val] val

Implements¶

SignedInteger[I16 val, U16 val] val

Constructors¶
create¶
[Source]


rewind¶
[Source]
fun ref rewind()
: None val

Returns¶

None val


fun box pdwait()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

exattr_delete¶
[Source]


fun ref i128_le(): I128 ? =>
"""
Get a little-endian I128.
"""
u128_le()?.i128()

fun ref f32_be(): F32 ? =>
"""
Get a big-endian F32.
"""
F32.from_bits(u32_be()?)

fun ref f32_le(): F32 ? =>
"""
Get a little-endian F32.
"""
F32.from_bits(u32_le()?)

fun ref f64_be(): F64 ? =>


y: U8 val

Returns¶

U8 val ?

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

Parameters¶

y: U8 val

Returns¶


I128 val

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

Parameters¶

y: I128 val

Returns¶

I128 val

mul_unsafe¶
[Source]


end
end
s'

fun eq(that: HashSet[A, H] box): Bool =>
"""
Return true if this and that contain the same elements.
"""
(size() == that.size()) and (this <= that)

fun lt(that: HashSet[A, H] box): Bool =>
"""
Return true if every element in this is also in that, and this has fewer
elements than that.
"""
(size() < that.size()) and (this <= that)

fun le(that: HashSet[A, H] box): Bool =>
"""
Return true if every element in this is also in that.


fun box usize()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64¶
[Source]


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


y: I16 val

Returns¶

I16 val

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

Parameters¶

y: I16 val

Returns¶


h.dispose_when_done(property_runner)
property_runner.run()


=>
match default'
| None => (typ', false, true)
| let d: _Value => (typ', d, false)
end

new val bool(
name': String,
descr': String = "",
short': (U8 | None) = None,
default': (Bool | None) = None)
=>
"""
Creates an Option with a Bool typed value that can be used like
`--opt` or `-O` or `--opt=true` or `-O=true`
to yield an option value like
`cmd.option("opt").bool() == true`.
"""
_name = name'
_descr = descr'


### Example

```pony
Iter[I64]([1; 2; 3].values())
.cycle()
```
`1 2 3 1 2 3 1 2 3 ...`
"""
let store = Array[A!]
Iter[A!](
object is Iterator[A!]
let _store: Array[A!] = store
var _store_iter: ArrayValues[A!, Array[A!]] = store.values()
var _first_time_through: Bool = true

fun ref has_next(): Bool => true

fun ref next(): A! ? =>
if _first_time_through then
if _iter.has_next() then


fun stopsig(wstatus: I32): I32 =>
exit_code(wstatus)

fun coredumped(wstatus: I32): Bool =>
(wstatus and 0x80) != 0

fun continued(wstatus: I32): Bool =>
wstatus == 0xffff

class _ProcessWindows is _Process
let h_process: USize
let process_error: (ProcessError | None)
var final_wait_result: (_WaitResult | None) = None

new create(
path: String,
args: Array[String] val,
vars: Array[String] val,
wdir: (FilePath | None),


for looping.
"""
let _prop1: Property1[T]
let _params: PropertyParams
let _rnd: Randomness
let _notify: PropertyResultNotify
let _gen: Generator[T]
let _logger: PropertyLogger
let _env: Env

// state changed during runtime
var _current_round: _Round = _Run.create(0)
"""
The number and kind of the round currently executed.
Keep track of which runs/shrinks we expect to be notified about.
"""
let _expected_actions: Set[String] = Set[String]
"""
List of expected actions for this round.
Will be cleared after each round.


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

eq¶
[Source]
Returns true if the sets contain the same elements.
fun box eq(
that: HashSet[A, H] box)
: Bool val

Parameters¶

that: HashSet[A, H] box

Returns¶

Bool val


Bool val

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

Parameters¶

that: box->A

Returns¶

Bool val

compare¶
[Source]


FormatFix val | FormatFixLarge val | FormatGeneral val |
FormatGeneralLarge val) = reference
prefix: (PrefixDefault val | PrefixSpace val | PrefixSign val) = reference
prec: USize val = 6
width: USize val = 0
align: (AlignLeft val | AlignRight val | AlignCenter val) = reference
fill: U32 val = 32

Returns¶

String iso^

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

Parameters¶


# With blocks

A `with` expression can be used to ensure disposal of an object when it is no longer needed. A common case is a database connection which needs to be closed after use to avoid resource leaks on the server. For example:

```pony
with obj = SomeObjectThatNeedsDisposing() do
// use obj
end
```

`obj.dispose()` will be called whether the code inside the `with` block completes successfully or raises an error. To take part in a `with` expression, the object that needs resource clean-up must, therefore, provide a `dispose()` method:

```pony
class SomeObjectThatNeedsDisposing
// constructor, other functions

fun dispose() =>
// release resources
```


fun box op_not()
: U64 val

Returns¶

U64 val

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

Parameters¶

y: U64 val

Returns¶


Returns¶

Nil[A] val

drop_while¶
[Source]
There are no elements to drop from the empty list.
fun box drop_while(
f: {(val->A): Bool}[A] box)
: Nil[A] val

Parameters¶

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

Returns¶

Nil[A] val


[Source]
fun box is_leaf()
: Bool val

Returns¶

Bool val

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

Returns¶

Bool val

help_name¶


32
33
34
35
36
37
38
39
40
41class XorShift128Plus is Random
"""
This is an implementation of xorshift+, as detailed at:

http://xoroshiro.di.unimi.it

This should only be used for legacy applications that specifically require
XorShift128Plus, otherwise use Rand.
"""
var _x: U64
var _y: U64


# Functions

Pony functions are quite like functions (or methods) in other languages. They can have 0 or more parameters and 0 or 1 return values. If the return type is omitted then the function will have a return value of `None`.

```pony
class C
fun add(x: U32, y: U32): U32 =>
x + y

fun nop() =>
add(1, 2)  // Pointless, we ignore the result
```

The function parameters (if any) are specified in parentheses after the function name. Functions that don't take any parameters still need to have the parentheses.

Each parameter is given a name and a type. In our example function `add` has 2 parameters, `x` and `y`, both of which are type `U32`. The values passed to a function call (the `1` and `2` in our example) are called arguments and when the call is made they are evaluated and assigned to the parameters. Parameters may not be assigned to within the function - they are effectively declared `let`.

After the parameters comes the return type. If nothing will be returned this is simply omitted.

After the return value, there's a `=>` and then finally the function body. The value returned is simply the value of the function body (remember that everything is an expression), which is simply the value of the last command in the function.


: (Array[Option] | SyntaxError)
=>
"""
if 'O' requires an argument
-OFoo  => -O has argument Foo
-O=Foo => -O has argument Foo
-O Foo => -O has argument Foo
else
-O=Foo => -O has argument foo
-abc => options a, b, c.
-abcFoo => options a, b, c. c has argument Foo iff its arg is required.
-abc=Foo => options a, b, c. c has argument Foo.
-abc Foo => options a, b, c. c has argument Foo iff its arg is required.
"""
let parts = token.split("=", 2)
let shorts = (try parts(0)? else "" end).clone()
var targ = try parts(1)? else None end

let options: Array[Option] ref = options.create()
while shorts.size() > 0 do


Calculate the hash of some type. This is an alias of the type parameter to
allow data structures to hash things without consuming them.
"""

fun eq(x: box->A!, y: box->A!): Bool
"""
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.
"""

primitive HashEq[A: (Hashable #read & Equatable[A] #read)] is HashFunction[A]
fun hash(x: box->A): USize =>
"""
Use the hash function from the type parameter.
"""
x.hash()

fun eq(x: box->A, y: box->A): Bool =>
"""


# How to modify a lexically captured variable in a closure

```pony
actor Main
fun foo(n:U32): {ref(U32): U32} =>
var s: Array[U32] = Array[U32].init(n, 1)
{ref(i:U32)(s): U32 =>
try
s(0)? = s(0)? + i
s(0)?
else
0
end
}

new create(env:Env) =>
var f = foo(5)
env.out.print(f(10).string())
env.out.print(f(20).string())
```


 PonyTest package

The PonyTest package provides a unit testing framework. It is designed to be as
simple as possible to use, both for the unit test writer and the user running
the tests.

To help simplify test writing and distribution this package depends on as few
other packages as possible. Currently the required packages are:

* builtin
* time
* collections

Each unit test is a class, with a single test function. By default all tests
run concurrently.

Each test run is provided with a helper object. This provides logging and
assertion functions. By default log messages are only shown for tests that
fail.


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


USize val

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

Returns¶

F32 val

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

Returns¶


A

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

Returns¶

USize val

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

Returns¶


# Nominal subtyping

This kind of subtyping is called __nominal__ because it is all about __names__.

If you've done object-oriented programming before, you may have seen a lot of discussion about _single inheritance_, _multiple inheritance_, _mixins_, _traits_, and similar concepts. These are all examples of __nominal subtyping__.

The core idea is that you have a type that declares it has a relationship to some category type. In Java, for example, a __class__ (a concrete type) can __implement__ an __interface__ (a category type). In Java, this means the class is now in the category that the interface represents. The compiler will check that the class actually provides everything it needs to.

In Pony, nominal subtyping is done via the keyword `is`. `is` declares at the point of declaration that an object has a relationship to a category type. For example, to use nominal subtyping to declare that the class `Name` provides `Stringable`, you'd do:

```pony
class Name is Stringable
```


: this->A ?

Parameters¶

i: USize val = 0

Returns¶

this->A ?

update¶
[Source]
Change the i-th element, raising an error if the index is out of bounds, and
returning the previous value.
let my_list = List[String].from(["a"; "b"; "c"])
try my_list.update(1, "z")? end // Returns "b" and List now contains ["a"; "z"; "c"]

fun ref update(
i: USize val,


if _bench_q.size() > 0 then
try
match _bench_q.shift()?
| (let b: MicroBenchmark, let overhead: Bool) =>
_RunSync(this, consume b, overhead)
| (let b: AsyncMicroBenchmark, let overhead: Bool) =>
_RunAsync(this, consume b, overhead)
end
end
else
_running = false
end

be _complete(results: _Results) =>
_output_manager(consume results)
_next_benchmark()

be _fail(name: String) =>
_env.err.print("Failed benchmark: " + name)
_env.exitcode(1)


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


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


fun box getsockname()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

listen¶
[Source]


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

Parameters¶

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


new val _descriptor(fd: I32, path: FilePath) ? =>
"""
This will raise an error if the FileStat capability isn't available or the
file descriptor is invalid.
"""
if not path.caps(FileStat) or (fd == -1) then
error
end

filepath = path

let fstat =
@pony_os_fstat(fd, path.path.cstring(), this)
if not fstat then error end

new val _relative(fd: I32, path: FilePath, from: String) ? =>
if not path.caps(FileStat) or (fd == -1) then
error
end


fun box lookup()
: U64 val

Returns¶

U64 val

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

Returns¶

U64 val

fchflags¶
[Source]


# Safely does it

__It is VERY important that when calling FFI functions you MUST get the parameter and return types right__. The compiler has no way to know what the native code expects and will just believe whatever you do. Errors here can cause invalid data to be passed to the FFI function or returned to Pony, which can lead to program crashes.

To help avoid bugs, Pony requires you to specify the type signatures of FFI functions in advance. While the compiler will trust that you specify the correct types in the signature, it will check the arguments you provide at each FFI call site against the declared signature. This means that you must get the types right only once, in the declaration. A declaration won't help you if the argument types the native code expects are different to what you think they are, but it will protect you against trivial mistakes and simple typos.

Here's an example of an FFI signature and call from the standard library:

```pony
use @_mkdir[I32](dir: Pointer[U8] tag) if windows
use @mkdir[I32](path: Pointer[U8] tag, mode: U32) if not windows

class val FilePath
fun val mkdir(must_create: Bool = false): Bool =>
// ...
let r = ifdef windows then
@_mkdir(element.cstring())
else
@mkdir(element.cstring(), 0x1FF)
end


Timers¶
[Source]
A hierarchical set of timing wheels.
actor tag Timers is
AsioEventNotify tag

Implements¶

AsioEventNotify tag

Constructors¶
create¶


y: A

Returns¶

A

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

Parameters¶

y: A

Returns¶


Parameters¶

y: A

Returns¶

(A , Bool val)

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

Parameters¶

y: A

Returns¶


712
713
714
715
716trait val _ArithmeticConvertible
fun i8(): I8 => compile_intrinsic
fun i16(): I16 => compile_intrinsic
fun i32(): I32 => compile_intrinsic
fun i64(): I64 => compile_intrinsic
fun i128(): I128 => compile_intrinsic
fun ilong(): ILong => compile_intrinsic
fun isize(): ISize => compile_intrinsic

fun u8(): U8 => compile_intrinsic
fun u16(): U16 => compile_intrinsic
fun u32(): U32 => compile_intrinsic
fun u64(): U64 => compile_intrinsic
fun u128(): U128 => compile_intrinsic
fun ulong(): ULong => compile_intrinsic
fun usize(): USize => compile_intrinsic


UDPNotify¶
[Source]
Notifications for UDP connections.
For an example of using this class please see the documentatoin for the
UDPSocket actor.
interface ref UDPNotify

Public Functions¶
listening¶
[Source]
Called when the socket has been bound to an address.
fun ref listening(
sock: UDPSocket ref)


write¶
[Source]
Returns false if the file wasn't opened with write permission.
Returns false and closes the file if not all the bytes were written.
fun ref write(
data: (String box | Array[U8 val] box))
: Bool val

Parameters¶

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

Returns¶

Bool val

writev¶
[Source]
Write an iterable collection of ByteSeqs.


[Source]
Clear the queue.
fun ref clear()
: None val

Returns¶

None val


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


end

offset = offset + num_bytes
_available = _available - num_bytes

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

fun ref i16_be(): I16 ? =>


fun ref i32()
: I32 val

Returns¶

I32 val

i64¶
[Source]
A random integer in [-2^63, 2^63)
fun ref i64()
: I64 val

Returns¶

I64 val

i128¶


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

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

Adjacent delimiters result in a zero length entry in the array. For
example, `"1,,2".split(",") => ["1", "", "2"]`.

If you want to split the string with the entire delimiter string `delim`,
use [`split_by`](#split_by).
"""
let result = recover Array[String] end


property_runner.pony

1
2
3
4
5
6
7
8
9
10
11


fun box so_listenqlimit()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_mark¶
[Source]


String iso^

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

Parameters¶

y: I16 val

Returns¶

I16 val

sub_unsafe¶
[Source]


CommandParser¶
[Source]
class ref CommandParser

Constructors¶
create¶
[Source]
Creates a new parser for a given command spec.
new box create(
spec': CommandSpec box)
: CommandParser box^

Parameters¶


let _out: OutStream

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

fun ref throttled(connection: TCPConnection ref) =>
_out.print("Experiencing backpressure!")
Backpressure.apply(_auth)

fun ref unthrottled(connection: TCPConnection ref) =>
_out.print("Releasing backpressure!")
Backpressure.release(_auth)

fun ref connect_failed(conn: TCPConnection ref) =>
None

actor Main
new create(env: Env) =>
let socket = TCPConnection(TCPConnectAuth(env.root),


Parameters¶

i: USize val

Returns¶

this->A ?

update_u8[optional B: (A & Real[B] val & U8 val)]¶
[Source]
Write a U8 at offset. This is only allowed for an array of U8s.
fun ref update_u8[optional B: (A & Real[B] val & U8 val)](
offset: USize val,
value: U8 val)
: U8 val ?

Parameters¶


fun mod_unsafe(y: F64): F64 =>
let r = this %~ y
if r == F64(0.0) then
r.copysign(y)
elseif (r > 0) xor (y > 0) then
r + y
else
r
end

fun finite(): Bool =>
"""
Check whether this number is finite, ie not +/-infinity and not NaN.
"""
// True if exponent is not all 1s
(bits() and 0x7FF0_0000_0000_0000) != 0x7FF0_0000_0000_0000

fun infinite(): Bool =>
"""
Check whether this number is +/-infinity


Array[A] ref^

Public Functions¶
cpointer¶
[Source]
Return the underlying C-style pointer.
fun box cpointer(
offset: USize val = 0)
: Pointer[A] tag

Parameters¶

offset: USize val = 0

Returns¶

Pointer[A] tag


in opposite sequential orders.

As you would expect. functions are provided to perform all the common list operations such as
creation, traversal, node addition and removal, iteration, mapping, filtering, etc.


predicate: Bool,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val
=>
"""
Assert that the given expression is false.
"""
if predicate then
_fail(_fmt_msg(loc, "Assert false failed. " + msg))
return false
end
_runner.log(_fmt_msg(loc, "Assert false passed. " + msg))
true

fun assert_true(
predicate: Bool,
msg: String val = "",
loc: SourceLoc val = __loc)
: Bool val


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


Add len elements to the end of the list, starting from the given
offset.
fun ref append(
seq: (ReadSeq[A] box & ReadElement[A^] box),
offset: USize val = 0,
len: USize val = call)
: None val

Parameters¶

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

Returns¶

None val

concat¶


52
53class Reverse[A: (Real[A] val & Number) = USize] is Iterator[A]
"""
Produces a decreasing range [max, min] with step `dec`, for any `Number` type.
(i.e. the reverse of `Range`)

Example program:

```pony
use "collections"
actor Main
new create(env: Env) =>
for e in Reverse(10, 2, 2) do
env.out.print(e.string())
end
```
Which outputs:
```
10
8


class iso _TestAdd is UnitTest
fun name(): String => "addition"

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

class iso _TestSub is UnitTest
fun name(): String => "subtraction"

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

The make() constructor is not needed for this example. However, it allows for easy aggregation of tests (see below) so it is recommended that all test Mains provide it.

Main.create() is called only for program invocations on the current package. Main.make() is called during aggregation. If so desired extra code can be added to either of these constructors to perform additional tasks.


None val ?

name¶
[Source]
Returns the name of this command.
fun box name()
: String val

Returns¶

String val

descr¶
[Source]
Returns the description for this command.
fun box descr()
: String val


type Number
interface OutStream
primitive Platform
struct Pointer
interface ReadElement
interface ReadSeq
trait Real
struct RuntimeOptions
interface Seq
type Signed
trait SignedInteger
interface SourceLoc
actor StdStream
actor Stdin
class String
class StringBytes
class StringRunes
interface Stringable
primitive U128
primitive U16


remove¶
[Source]
Remove everything that is in that.
fun ref remove(
that: Iterator[box->A!] ref)
: None val

Parameters¶

that: Iterator[box->A!] ref

Returns¶

None val

add[optional K: HashFunction[this->A!] val]¶
[Source]
Add a value to the set.
fun box add[optional K: HashFunction[this->A!] val](


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


primitive FormatHexSmall is FormatSpec
primitive FormatHexSmallBare is FormatSpec

type FormatInt is
( FormatDefault
| FormatUTF32
| FormatBinary
| FormatBinaryBare
| FormatOctal
| FormatOctalBare
| FormatHex
| FormatHexBare
| FormatHexSmall
| FormatHexSmallBare )

primitive FormatExp is FormatSpec
primitive FormatExpLarge is FormatSpec
primitive FormatFix is FormatSpec
primitive FormatFixLarge is FormatSpec
primitive FormatGeneral is FormatSpec


try
if is_sep(path(path.size()-1)?) then
if is_sep(next_path(0)?) then
return clean(path + next_path.trim(1))
else
return clean(path + next_path)
end
end
end
clean(path + sep() + next_path)
end

fun clean(path: String): String =>
"""
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 sctp_pcb_flags_accepting()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

sctp_pcb_flags_assoc_resetevnt¶
[Source]


actor Custodian
actor Registrar


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


# How does this help?

Instead of having permissions lists, access control lists, or other forms of security, the object-capabilities model means that if you have a reference to an object, you can do things with that object. Simple and effective.

There's a great paper on how the object-capability model works, and it's pretty easy reading:

[Capability Myths Demolished](http://srl.cs.jhu.edu/pubs/SRL2003-02.pdf)


ArgSpec val

bool¶
[Source]
Returns the arg value as a Bool, defaulting to false.
fun box bool()
: Bool val

Returns¶

Bool val

string¶
[Source]
Returns the arg value as a String, defaulting to empty.
fun box string()
: String val


let _out: OutStream
let _path: (FilePath | None)
embed _history: Array[String]
embed _queue: Array[String] = Array[String]
let _maxlen: USize

var _edit: String iso = recover String end
var _cur_prompt: String = ""
var _cur_line: USize = 0
var _cur_pos: ISize = 0
var _blocked: Bool = true

new iso create(
notify: ReadlineNotify iso,
out: OutStream,
path: (FilePath | None) = None,
maxlen: USize = 0)
=>
"""
Create a readline handler to be passed to stdin. It begins blocked. Set an


fun box addc(
y: U32 val)
: (U32 val , Bool val)

Parameters¶

y: U32 val

Returns¶

(U32 val , Bool val)

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

Parameters¶


system call's `sockopt_len_t *` 5th argument.

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

Usage example:

```pony
// connected() is a callback function for class TCPConnectionNotify
fun ref connected(conn: TCPConnection ref) =>
match conn.getsockopt(OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(), 4)
| (0, let gbytes: Array[U8] iso) =>
try
let br = Reader.create().>append(consume gbytes)
ifdef littleendian then
let buffer_size = br.u32_le()?
else
let buffer_size = br.u32_be()?
end


fun box so_broadcast()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_bsp_state¶
[Source]


new ref create(
x: U64 val = 5489,
y: U64 val = 0)
: Random ref^

Parameters¶

x: U64 val = 5489
y: U64 val = 0

Returns¶

Random ref^

Public Functions¶
has_next¶
[Source]
If used as an iterator, this always has another value.
fun tag has_next()


Bool val

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

Returns¶

Bool val

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

Returns¶


fun box mul(
y: ULong val)
: ULong val

Parameters¶

y: ULong val

Returns¶

ULong val

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

Parameters¶


else
false
end
else
false
end
end

fun ref next(): B ? =>
if _iterb.has_next() then
_iterb.next()?
else
_iterb = f(_iter.next()?)?
next()?
end
end)

fun ref fold[B](acc: B, f: {(B, A!): B^} box): B^ =>
"""
Apply a function to every element, producing an accumulated value.


for c in cols.values() do
(let c0, let c1, _) = c
let c1s = c0 + c1.size()
if c1s > widest then
widest = c1s
end
end
for c in cols.values() do
(let c0, let c1, let c2) = c
indent(w, 1 + c0)
w.write(c1)
indent(w, (widest - c1.size()) + 2)
w.write(c2 + "\n")
end


| `val`               | reference capability – globally immutable object                                                       |
| `where`             | when specifying named arguments                                                                        |
| `while`             | loop statement                                                                                |
| `with`              | ensure disposal of an object                                                                           |


_event = AsioEvent.none()
end
end

fun ref _fire(timer: Timer) =>
"""
Fire a timer if necessary, then schedule it on the correct timing wheel
based on how long it is until it expires.
"""
if not timer._fire(_current) then
try
_map.remove(timer)?
end
return
end

try
let rem = timer._next() - _current
_get_wheel(rem)?.schedule(consume timer)
end


rejected: Reject[Promise[B] tag] iso = qualify

Returns¶

Promise[B] tag

add[optional B: Any #share]¶
[Source]
Add two promises into one promise that returns the result of both when
they are fulfilled. If either of the promises is rejected then the new
promise is also rejected.
fun tag add[optional B: Any #share](
p: Promise[B] tag)
: Promise[(A , B)] tag

Parameters¶

p: Promise[B] tag


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


n: USize val

Returns¶

None val ?

block¶
[Source]
Return a block as a contiguous chunk of memory.
Will throw an error if you request a block larger than what is currently
stored in the Reader.
fun ref block(
len: USize val)
: Array[U8 val] iso^ ?

Parameters¶

len: USize val


listen: TCPListener ref)
: None val

Parameters¶

listen: TCPListener ref

Returns¶

None val

closed¶
[Source]
Called when the listener is closed.
fun ref closed(
listen: TCPListener ref)
: None val

Parameters¶


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


Clear the queue.
"""
_array.clear()
_write = 0


return _array(i)? as (_, V)
else
let key' = key

_array(i)? = (consume key, consume value)
_size = _size + 1

if (_size * 4) > (_array.size() * 3) then
_resize(_array.size() * 2)
end
end

value'
else
// This is unreachable, since index will never be out-of-bounds
value'
end

fun ref insert(key: K, value: V): V! =>
"""


Unsafe operation.
If the value doesn't fit in the destination type, the result is undefined.
"""
compile_intrinsic

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

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

fun ilong_unsafe(): ILong =>


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

fun bitwidth(): U8 => 8

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

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

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

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


U32 val

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

Parameters¶

y: U32 val

Returns¶

U32 val

op_or¶
[Source]


fun box u32()
: U32 val

Returns¶

U32 val

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

Returns¶

U64 val

u128¶
[Source]


: SetValues[A, H, this->HashSet[A, H] ref] ref^

Returns¶

SetValues[A, H, this->HashSet[A, H] ref] ref^

compare¶
[Source]
fun box compare(
that: HashSet[A, H] box)
: (Less val | Equal val | Greater val)

Parameters¶

that: HashSet[A, H] box

Returns¶

(Less val | Equal val | Greater val)


fun tag benchmarks(bench: PonyBench) =>
bench(_Nothing)
bench(_Fib(5))
bench(_Fib(10))
bench(_Fib(20))
bench(_Timer(10_000))

class iso _Nothing is MicroBenchmark
// Benchmark absolutely nothing.
fun name(): String => "Nothing"

fun apply() =>
// prevent compiler from optimizing out this operation
DoNotOptimise[None](None)
DoNotOptimise.observe()

class iso _Fib is MicroBenchmark
// Benchmark non-tail-recursive fibonacci
let _n: U64


new create(seq: Seq[T]) =>
_seq = seq

new empty() =>
_seq = Array[T](0)

fun ref has_next(): Bool =>
_seq.size() > 0

fun ref next(): T^ ? =>
_seq.pop()?


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


InputSerialisedAuth¶
[Source]
This is a capability token that allows the holder to treat arbitrary
bytes as serialised data. This is the most dangerous capability, as currently
it is possible for a malformed chunk of data to crash your program if it is
deserialised.
primitive val InputSerialisedAuth

Constructors¶
create¶
[Source]
new val create(
auth: AmbientAuth val)


# Bare lambdas

Bare lambdas are special lambdas defining bare functions. A bare lambda or bare lambda type is specified using the same syntax as other lambda types, with the small variation that it is prefixed with the @ symbol. The underlying value of a bare lambda is equivalent to a C function pointer, which means that a bare lambda can be directly passed as a callback to a C function. The partial application of a bare method yields a bare lambda.

```pony
let callback = @{() => ... }
@setup_callback(callback)
```

Bare lambdas can also be used to define structures containing function pointers. For example:

```pony
struct S
var fun_ptr: @{()}
```

This Pony structure is equivalent to the following C structure:

```c
struct S


[Source]
Called when multiple chunks of data are sent to the connection in a single
call. This gives the notifier an opportunity to modify the sent data chunks
before they are written. To swallow the send, return an empty
Array[String].
fun ref sentv(
conn: TCPConnection ref,
data: ByteSeqIter val)
: ByteSeqIter val

Parameters¶

conn: TCPConnection ref
data: ByteSeqIter val

Returns¶

ByteSeqIter val


that._int_shrink[I64](consume i, min)
end)

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

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


_set.set(v)
v
end
end)

fun ref zip[B](i2: Iterator[B]): Iter[(A, B)]^ =>
"""
Zip two iterators together so that each call to next() results in
a tuple with the next value of the first iterator and the next value
of the second iterator. The number of items returned is the minimum of
the number of items returned by the two iterators.


_notify.page_up(ctrl, alt, shift)
_esc_clear()

fun ref _page_down() =>
"""
Page down key.
"""
(let ctrl, let alt, let shift) = _mod()
_notify.page_down(ctrl, alt, shift)
_esc_clear()

fun ref _fn_key(i: U8) =>
"""
Function key.
"""
(let ctrl, let alt, let shift) = _mod()
_notify.fn_key(i, ctrl, alt, shift)
_esc_clear()

fun ref _esc_flush() =>


: None val

Parameters¶

node: ListNode[A] ref

Returns¶

None val

append_node¶
[Source]
Adds a node to the tail of the list.
let my_list = List[String].from(["a"; "b"; "c"])
let new_tail = ListNode[String]("0")
my_list.append_node(new_head) // ["a"; "b"; "c", "0"]

fun ref append_node(
node: ListNode[A] ref)


(A , Bool val)

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

Parameters¶

y: A

Returns¶

A ?

mod_unsafe¶


fun take_while(f: {(val->A): Bool} box): Nil[A] =>
"""
There are no elements to take from the empty list.
"""
this

fun val contains[T: (A & HasEq[A!] #read) = A](a: val->T): Bool =>
false

class val Cons[A] is ReadSeq[val->A]
"""
A list with a head and a tail, where the tail can be empty.
"""

let _size: USize
let _head: val->A
let _tail: List[A] val

new val create(a: val->A, t: List[A]) =>
_head = consume a


=>
...
```

```pony
use @sqlite3_exec[I32](db: Pointer[None] tag, sql: Pointer[U8] tag,
callback: Pointer[None], data: Pointer[None], err_msg: Pointer[Pointer[U8] tag] tag)

class SQLiteClient
fun client_code() =>
...
let lambda_callback =
@{(client: SQLiteClient, argc: I32, argv: Pointer[Pointer[U8]],
azColName: Pointer[Pointer[U8]]): I32
=>
...
}

@sqlite3_exec(db, sql.cstring(), lambda_callback, this,
addressof zErrMsg)


_fold[B](this, f, consume acc)

fun val _fold[B](l: List[A], f: {(B, val->A): B^} box, acc: B): B =>
"""
Private helper for fold, recursively working on elements.
"""
match l
| let cons: Cons[A] =>
_fold[B](cons.tail(), f, f(consume acc, cons.head()))
else
acc
end

fun val every(f: {(val->A): Bool} box): Bool =>
"""
Returns true if every element satisfies the provided predicate, false
otherwise.
"""
_every(this, f)


fun box usize()
: USize val

Returns¶

USize val

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

Returns¶

F32 val

f64¶
[Source]


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


# The compiler

Pony is a _compiled_ language, rather than an _interpreted_ one. In fact, it goes even further: Pony is an _ahead-of-time_ (AOT) compiled language, rather than a _just-in-time_ (JIT) compiled language.

What this means is that once you build your program, you can run it over and over again without needing a compiler or a virtual machine or anything else. It's a complete program, all on its own.

But it also means you need to build your program before you can run it. In an interpreted language or a JIT compiled language, you tend to do things like this to run your program:

```bash
python helloworld.py
```

Or maybe you put a __shebang__ in your program (like `#!/usr/bin/env python`), then `chmod` to set the executable bit, and then do:

```bash
./helloworld.py
```

When you use Pony, you don't do any of that!


U64 val

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

Returns¶

U128 val

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

Returns¶


unsigned.pony

1
2
3
4
5
6
7
8
9
10
11


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


"""
var i: ISize = 0
var n: USize = 0

try
while true do
i = find(s, i)?
cut_in_place(i, i + s.size().isize())
n = n + 1
end
end
n

fun ref replace(from: String box, to: String box, n: USize = 0): USize =>
"""
Replace up to n occurrences of `from` in `this` with `to`. If n is 0, all
occurrences will be replaced. Returns the count of replaced occurrences.
"""
let from_len = from.size().isize()
let to_len = to.size().isize()


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


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


fun box ipv6_mtu_discover()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_multicast_if¶
[Source]


fun ipx_primary():I32 => @pony_os_sockopt_option(I32(222))
fun ipx_ptype():I32 => @pony_os_sockopt_option(I32(223))
fun ipx_receive_broadcast():I32 => @pony_os_sockopt_option(I32(224))
fun ipx_recvhdr():I32 => @pony_os_sockopt_option(I32(225))
fun ipx_reripnetnumber():I32 => @pony_os_sockopt_option(I32(226))
fun ipx_route_no_router():I32 => @pony_os_sockopt_option(I32(227))
fun ipx_rt_8022():I32 => @pony_os_sockopt_option(I32(228))
fun ipx_rt_bluebook():I32 => @pony_os_sockopt_option(I32(229))
fun ipx_rt_routed():I32 => @pony_os_sockopt_option(I32(230))
fun ipx_rt_snap():I32 => @pony_os_sockopt_option(I32(231))
fun ipx_special_none():I32 => @pony_os_sockopt_option(I32(232))
fun ipx_spxgetconnectionstatus():I32 => @pony_os_sockopt_option(I32(233))
fun ipx_stopfilterptype():I32 => @pony_os_sockopt_option(I32(234))
fun ipx_type():I32 => @pony_os_sockopt_option(I32(235))
fun ip_add_membership():I32 => @pony_os_sockopt_option(I32(236))
fun ip_add_source_membership():I32 => @pony_os_sockopt_option(I32(237))
fun ip_bindany():I32 => @pony_os_sockopt_option(I32(238))
fun ip_bindmulti():I32 => @pony_os_sockopt_option(I32(239))
fun ip_bind_address_no_port():I32 => @pony_os_sockopt_option(I32(240))
fun ip_block_source():I32 => @pony_os_sockopt_option(I32(241))


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


prompt¶
[Source]
Set a new prompt, unblock, and handle the pending queue.
fun ref prompt(
term: ANSITerm ref,
value: String val)
: None val

Parameters¶

term: ANSITerm ref
value: String val

Returns¶

None val

closed¶


primitive Format
primitive FormatBinary
primitive FormatBinaryBare
primitive FormatDefault
primitive FormatExp
primitive FormatExpLarge
primitive FormatFix
primitive FormatFixLarge
type FormatFloat
primitive FormatGeneral
primitive FormatGeneralLarge
primitive FormatHex
primitive FormatHexBare
primitive FormatHexSmall
primitive FormatHexSmallBare
type FormatInt
primitive FormatOctal
primitive FormatOctalBare
trait FormatSpec
primitive FormatUTF32


_next = None
| (None, None) =>
// We're the only member
list'._set_head(None)
list'._set_tail(None)
end

list'._decrement()
_list = None
end

fun has_prev(): Bool =>
"""
Return true if there is a previous node.
"""
_prev isnt None

fun has_next(): Bool =>
"""
Return true if there is a next node.


# Privacy

In Pony, method names start either with a lower case letter or with an underscore followed by a lowercase letter. Methods with a leading underscore are private. This means they can only be called by code within the same package. Methods without a leading underscore are public and can be called by anyone.

__Can I start my method name with 2 (or more) underscores?__ No. If the first character is an underscore then the second one MUST be a lower case letter.


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


| WaitpidError
| WriteError
| KillError
| CapError
| ChdirError
| UnknownError
)

primitive ExecveError
fun string(): String iso^ => "ExecveError".clone()

primitive PipeError
fun string(): String iso^ => "PipeError".clone()

primitive ForkError
fun string(): String iso^ => "ForkError".clone()

primitive WaitpidError
fun string(): String iso^ => "WaitpidError".clone()


Public Functions¶
reserve¶
[Source]
Do nothing
Required method for List to satisfy the Seq interface.
fun ref reserve(
len: USize val)
: None val

Parameters¶

len: USize val

Returns¶

None val

size¶
[Source]


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


target: String val
atime: (I64 val , I64 val)
mtime: (I64 val , I64 val)

Returns¶

Bool val

symlink¶
[Source]
Link the source path to the link_name, where the link_name is relative to
this directory.
fun box symlink(
source: FilePath val,
link_name: String val)
: Bool val

Parameters¶


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851


USize val

codepoints¶
[Source]
Returns the number of unicode code points in the string between the two
offsets. Index range [from .. to) is half-open.
fun box codepoints(
from: ISize val = 0,
to: ISize val = call)
: USize val

Parameters¶

from: ISize val = 0
to: ISize val = call

Returns¶


Returns¶

BenchConfig val

overhead¶
[Source]
fun box overhead()
: AsyncMicroBenchmark iso^

Returns¶

AsyncMicroBenchmark iso^

before¶
[Source]
fun ref before(
c: AsyncBenchContinue val)
: None val


# Labels

Test can have label. Labels are used to filter which tests are run, by setting
command line argument `--label=[some custom label]`. It can be used to separate
unit tests from integration tests.

By default label is empty. You can set it up by overriding `label(): String`
method in unit test.

```pony
use "pony_test"

class iso _I8AddTest is UnitTest
fun name(): String => "_I8AddTest"
fun label(): String => "simple"
fun apply(h: TestHelper) =>
h.assert_eq[I8](1, 1)

```


U128 val

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

Returns¶

ULong val

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

Returns¶


gen¶
[Source]
fun box gen()
: Generator[(T1 , T2 , T3 , T4)] box

Returns¶

Generator[(T1 , T2 , T3 , T4)] box

property¶
[Source]
fun ref property(
arg1: (T1 , T2 , T3 ,
T4),
h: PropertyHelper val)
: None val ?


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


(U64 val , U64 val)

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

Parameters¶

y: U64 val

Returns¶

U64 val

neg¶
[Source]


fun box ctz_unsafe()
: USize val

Returns¶

USize val

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

Returns¶

USize val

bytewidth¶
[Source]


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


interface WalkHandler
"""
A handler for `FilePath.walk`.
"""
fun ref apply(dir_path: FilePath, dir_entries: Array[String] ref)

class val FilePath
"""
A FilePath represents a capability to access a path. The path will be
represented as an absolute path and a set of capabilities for operations on
that path.
"""
let path: String
"""
Absolute filesystem path.
"""
let caps: FileCaps = FileCaps
"""
Set of capabilities for operations on `path`.


Returns¶

Bool val


## String Literals and Encodings

String Literals contain the bytes that were read from their source code file. Their actual value thus depends on the encoding of their source.

Consider the following example:

```pony
let u_umlaut = "ü"
```

If the file containing this code is encoded as `UTF-8` the byte-value of `u_umlaut` will be: `\xc3\xbc`. If the file is encoded with *ISO-8559-1* (Latin-1) its value will be `\xfc`.


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


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


Join three existing promises to make a fourth.
```pony
use "promises"

actor Main
new create(env: Env) =>

let p1 = Promise[String val]
let p2 = Promise[String val]
let p3 = Promise[String val]

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

p2("second")
p3("third")


fun box remc(
y: U16 val)
: (U16 val , Bool val)

Parameters¶

y: U16 val

Returns¶

(U16 val , Bool val)

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

Parameters¶


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


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


new val create(
value: A)
: Real[A] val^

Parameters¶

value: A

Returns¶

Real[A] val^

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


292
293
294
295
296
297
298
299
300
301
302
303primitive ANSI
"""
These strings can be embedded in text when writing to a StdStream to create
a text-based UI.
"""
fun up(n: U32 = 0): String =>
"""
Move the cursor up n lines. 0 is the same as 1.
"""


end
```


ISize val

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

Parameters¶

y: ISize val

Returns¶

ISize val

divrem_unsafe¶


fun box ip_rss_listen_bucket()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ip_rsvp_on¶
[Source]


# FFI functions raising errors

Some FFI functions might raise Pony errors. Functions in existing C libraries are very unlikely to do this, but support libraries specifically written for use with Pony may well do.

FFI calls to functions that __might__ raise an error __must__ mark it as such by adding a ? after its declaration. The FFI call site must mark it as well. For example:

```pony
use @pony_os_send[USize](event: AsioEventID, buffer: Pointer[U8] tag, size: USize) ?
// ...
// May raise an error
@pony_os_send(_event, data.cpointer(), data.size()) ?
```

If you're writing a C library that wants to raise a Pony error, you should do so using the `pony_error` function. Here's an example from the Pony runtime:

```C
// In pony.h
PONY_API void pony_error();

// In socket.c


(U32 val , U32 val) ?

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

Parameters¶

y: U32 val

Returns¶

U32 val

shr¶
[Source]


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


Returns the next line in the file.
"""
while true do
try
return _read_line()?
else
if not _fill_buffer() then
// nothing to read from file, we can savely exit here
break
end
end
end
_has_next = false
if _reader.size() > 0 then
// don't forget the last line
_read_last_line()?
else
// nothing to return, we can only error here
error
end


arg1: T1
arg2: T2
h: PropertyHelper val

Returns¶

None val ?

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

Returns¶

String val

params¶


implment the Fulfill and Reject interfaces, or as functions with
the same signatures as the apply methods in Fulfill and Reject.
In the following code, the fulfillment of the Promise causes the
execution of several fulfillment functions. The output is:
fulfilled + foo
fulfilled + bar
fulfilled + baz

use "promises"

class PrintFulfill is Fulfill[String, String]
let _env: Env
let _msg: String
new create(env: Env, msg: String) =>
_env = env
_msg = msg
fun apply(s: String): String =>
_env.out.print(" + ".join([s; _msg].values()))
s


SplitMix64¶
[Source]
Very fast Pseudo-Random-Number-Generator
using only 64 bit of state, as detailed at:
http://xoshiro.di.unimi.it/ and http://gee.cs.oswego.edu/dl/papers/oopsla14.pdf
Using XorOshiro128StarStar or XorOshiro128Plus
should be prefered unless using only 64 bit of state is a requirement.
class ref SplitMix64 is
Random ref

Implements¶

Random ref


fun ipv6_recvpathmtu():I32 => @pony_os_sockopt_option(I32(182))
fun ipv6_recvpktinfo():I32 => @pony_os_sockopt_option(I32(183))
fun ipv6_recvrthdr():I32 => @pony_os_sockopt_option(I32(184))
fun ipv6_recvtclass():I32 => @pony_os_sockopt_option(I32(185))
fun ipv6_router_alert():I32 => @pony_os_sockopt_option(I32(186))
fun ipv6_rthdr():I32 => @pony_os_sockopt_option(I32(187))
fun ipv6_rthdrdstopts():I32 => @pony_os_sockopt_option(I32(188))
fun ipv6_tclass():I32 => @pony_os_sockopt_option(I32(189))
fun ipv6_tlv_hao():I32 => @pony_os_sockopt_option(I32(190))
fun ipv6_tlv_jumbo():I32 => @pony_os_sockopt_option(I32(191))
fun ipv6_tlv_pad1():I32 => @pony_os_sockopt_option(I32(192))
fun ipv6_tlv_padn():I32 => @pony_os_sockopt_option(I32(193))
fun ipv6_tlv_routeralert():I32 => @pony_os_sockopt_option(I32(194))
fun ipv6_transparent():I32 => @pony_os_sockopt_option(I32(195))
fun ipv6_unicast_hops():I32 => @pony_os_sockopt_option(I32(196))
fun ipv6_unicast_if():I32 => @pony_os_sockopt_option(I32(197))
fun ipv6_use_min_mtu():I32 => @pony_os_sockopt_option(I32(198))
fun ipv6_v6only():I32 => @pony_os_sockopt_option(I32(199))
fun ipv6_xfrm_policy():I32 => @pony_os_sockopt_option(I32(200))
fun ipx_address():I32 => @pony_os_sockopt_option(I32(201))


## Immutable data can be safely shared

Any data that is immutable (i.e. it cannot be changed) is safe to use concurrently. Since it is immutable it is never updated and it's the updates that cause concurrency problems.


_runner.log(_fmt_msg(loc, "Assert no error passed. " + msg), true)
true
else
_fail(_fmt_msg(loc, "Assert no error failed. " + msg))
false
end

fun assert_is[A](
expect: A,
actual: A,
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>
"""
Assert that the 2 given expressions resolve to the same instance.
"""
if expect isnt actual then
_fail(_fmt_msg(loc, "Assert is failed. " + msg
+ " Expected (" + (digestof expect).string() + ") is ("


[Source]
Returns a pseudo-random base, suitable as a temporary file name or
directory name, but not guaranteed to not already exist.
fun box random(
len: USize val = 6)
: String val

Parameters¶

len: USize val = 6

Returns¶

String val

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


Note that memory is not freed by this operation.
fun ref truncate(
len: USize val)
: None val

Parameters¶

len: USize val

Returns¶

None val

trim_in_place¶
[Source]
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.
fun ref trim_in_place(


corresponding servicename (e.g. port 80 is returned as `"http"`).

Internally this method uses the POSIX C function `getnameinfo`.
"""
var host: Pointer[U8] iso = recover Pointer[U8] end
var serv: Pointer[U8] iso = recover Pointer[U8] end
let reverse = reversedns isnt None

if not
@pony_os_nameinfo(this, addressof host, addressof serv, reverse,
servicename)
then
error
end

(recover String.from_cstring(consume host) end,
recover String.from_cstring(consume serv) end)

fun eq(that: NetAddress box): Bool =>
(this._family == that._family)


iso_array¶
[Source]
Returns an Array[U8] iso that reuses the underlying data pointer.
fun iso iso_array()
: Array[U8 val] iso^

Returns¶

Array[U8 val] iso^

size¶
[Source]
Returns the length of the string data in bytes.
fun box size()
: USize val

Returns¶


new val create()
: FormatExpLarge val^

Returns¶

FormatExpLarge val^

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

Parameters¶

that: FormatExpLarge val

Returns¶


y: U16 val

Returns¶

U16 val ?

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

Parameters¶

y: U16 val

Returns¶


actor StdStream
"""
Asynchronous access to stdout and stderr. The constructors are private to
ensure that access is provided only via an environment.
"""
var _stream: Pointer[U8]

new _out() =>
"""
Create an async stream for stdout.
"""
_stream = @pony_os_stdout()

new _err() =>
"""
Create an async stream for stderr.
"""
_stream = @pony_os_stderr()

be print(data: ByteSeq) =>


(_, let found) = _search(k)
found

fun ref concat(iter: Iterator[(K^, V^)]) =>
"""
Add K, V pairs from the iterator to the map.
"""
for (k, v) in iter do
this(consume k) = consume v
end

fun add[H2: HashFunction[this->K!] val = H](
key: this->K!,
value: this->V!)
: HashMap[this->K!, this->V!, H2]^
=>
"""
This with the new (key, value) mapping.
"""
let r = clone[H2]()


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


AmbientAuth¶
[Source]
This type represents the root capability. When a Pony program starts, the
Env passed to the Main actor contains an instance of the root capability.
Ambient access to the root capability is denied outside of the builtin
package. Inside the builtin package, only Env creates a Root.
The root capability can be used by any package that wants to establish a
principle of least authority. A typical usage is to have a parameter on a
constructor for some resource that expects a limiting capability specific to
the package, but will also accept the root capability as representing
unlimited access.
primitive val AmbientAuth


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

Parameters¶

y: U64 val

Returns¶

(U64 val , Bool val)

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

Parameters¶


give access to the root authority and other stuff.
class val PropertyHelper

Constructors¶
create¶
[Source]
new val create(
env': Env val,
runner: _IPropertyRunner tag,
run_notify: _PropertyRunNotify val,
run: (_Shrink val | _Run val),
params: String val)
: PropertyHelper val^

Parameters¶

env': Env val
runner: _IPropertyRunner tag
run_notify: _PropertyRunNotify val
run: (_Shrink val | _Run val)


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


blink¶
[Source]
Blinking text. Does nothing on Windows.
fun box blink(
state: Bool val = true)
: String val

Parameters¶

state: Bool val = true

Returns¶

String val

reverse¶
[Source]


let len = _search_length()?

_available = _available - len
var out = recover String(len) end
var i = USize(0)

while i < len do
let node = _chunks.head()?
(let data, let offset) = node()?

let avail = data.size() - offset
let need = len - i
let copy_len = need.min(avail)

out.append(data, offset, copy_len)

if avail > need then
node()? = (data, offset + need)
break
end


1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591


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


Public Functions¶
signature¶
[Source]
Returns a byte array that is unique to this compiled Pony binary, for the
purposes of comparing before deserialising any data from that source.
It is statistically impossible for two serialisation-incompatible Pony
binaries to have the same serialise signature.
fun box signature()
: Array[U8 val] val

Returns¶

Array[U8 val] val

eq¶
[Source]
fun box eq(


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

Parameters¶

that: AmbientAuth val

Returns¶

Bool val

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


# Using a type parameter as a viewpoint

We haven't covered generics yet, so this may seem a little weird. We'll cover this again when we talk about generics (i.e. parameterised types), but we're mentioning it here for completeness.

Another time we don't know the precise reference capability of something is if we are using a type parameter. Here's an example from the standard library:

```pony
class ListValues[A, N: ListNode[A] box] is Iterator[N->A]
```

Here, we have a `ListValues` type that has two type parameters, `A` and `N`. In addition, `N` has a constraint: it has to be a subtype of `ListNode[A] box`. That's all fine and well, but we also say the `ListValues[A, N]` provides `Iterator[N->A]`. That's the interesting bit: we provide an interface that let's us iterate over values of the type `N->A`.

That means we'll be returning objects of the type `A`, but the reference capability will be the same as an object of type `N` would see an object of type `A`.


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

Parameters¶

y: A

Returns¶

A

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

Returns¶


### Unsafe Conversion

Converting between integer types in Pony needs to happen explicitly. Each numeric type can be converted explicitly into every other type.

```pony
// converting an I32 to a 32 bit floating point
I32(12).f32()
```

For each conversion operation there exists an unsafe counterpart, that is much faster when converting from and to floating point numbers. All these unsafe conversion between numeric types are undefined if the target type is smaller than the source type, e.g. if we convert from `I64` to `F32`.

```pony
// converting an I32 to a 32 bit floating point, the unsafe way
I32(12).f32_unsafe()

// an example for an undefined unsafe conversion
I64.max_value().f32_unsafe()

// an example for an undefined unsafe conversion, that is actually safe
I64(1).u8_unsafe()


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


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

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

fun byte_string(
gen: Generator[U8],


fun box eq(
other: (Exited val | Signaled val))
: Bool val

Parameters¶

other: (Exited val | Signaled val)

Returns¶

Bool val

ne¶
[Source]
fun box ne(
that: (Exited val | Signaled val))
: Bool val

Parameters¶


`qty` is zero, the call can contain any amount of data.
"""
_expect = _notifier.expect(this, qty)
_read_buf_size()

be _event_notify(event: AsioEventID, flags: U32, arg: U32) =>
"""
Handle the incoming Asio event from one of the pipes.
"""
match event
| _stdin.event =>
if AsioEvent.writeable(flags) then
_pending_writes()
elseif AsioEvent.disposable(flags) then
_stdin.dispose()
end
| _stdout.event =>
if AsioEvent.readable(flags) then
_pending_reads(_stdout)
elseif AsioEvent.disposable(flags) then


fun ref connected(conn: TCPConnection ref) =>
conn.write("hello world")

fun ref received(
conn: TCPConnection ref,
data: Array[U8] iso,
times: USize)
: Bool
=>
_out.print("GOT:" + String.from_array(consume data))
conn.close()
true

fun ref connect_failed(conn: TCPConnection ref) =>
None

actor Main
new create(env: Env) =>
TCPConnection(TCPConnectAuth(env.root),


=>
sock.write(consume data, from)

fun ref not_listening(sock: UDPSocket ref) =>
None

actor Main
new create(env: Env) =>
UDPSocket(UDPAuth(env.root),
MyUDPNotify, "", "8989")
```

The client is implemented like this:

```pony
use "net"

class MyUDPNotify is UDPNotify
let _out: OutStream
let _destination: NetAddress


fun box so_rcvlowat()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_rds_transport¶
[Source]


let max_sample_time: U64 val¶
[Source]
Maximum time to execute a sample in Nanoseconds. (Default: 100_000_000)


ubuff[2] = (sz >> 8) & 0xFF;
ubuff[3] = sz & 0xFF;

// copy the string
strncpy(buff + 4, s, sz);
}

extern char *deserialise(char *buff)
{
unsigned char *ubuff = (unsigned char *) buff;
size_t sz = (ubuff[0] << 24) + (ubuff[1] << 16) + (ubuff[2] << 8) + ubuff[3];
char *s = malloc(sizeof(char) * sz + 1);
memcpy(s, buff + 4, sz);
s[sz] = '\0';
return s;
}
```


fun box so_atmsap()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

so_attach_filter¶
[Source]


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

Parameters¶

msg: Stringable box = ""

Returns¶

None val

eq¶
[Source]


String iso^

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

Parameters¶

y: A

Returns¶

A

sub_unsafe¶


# Example program
The functions which are illustrated below are only those which operate on an
individual ListNode.

It outputs:

My node has the item value: My Node item
My node has the updated item value: My updated Node item
Popped the item from the ListNode
The ListNode has no (None) item.

```pony
use "collections"
actor Main
new create(env:Env) =>

// Create a new ListNode of type String
let my_list_node = ListNode[String]("My Node item")
try
env.out.print("My node has the item value: "


let path: FilePath
"""
This is the filesystem path locating this directory on the file system
and an object capability granting access to operate on this directory.
"""

var _fd: I32 = -1
// We don't need a file descriptor in Windows. However we do still need to
// know whether we've disposed of this object, so we use the _fd to indicate
// this.
// 0 => not yet disposed of.
// -1 => disposed of.

new create(from: FilePath) ? =>
"""
This will raise an error if the path doesn't exist or it is not a
directory, or if FileRead or FileStat permission isn't available.
"""
if not from.caps(FileRead) then
error


true
else
false
end

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

i = i + 1
end
error

fun rfind(s: String box, offset: ISize = -1, nth: USize = 0): ISize ? =>
"""
Return the index of n-th instance of `s` in the string starting from the
end. The `offset` represents the highest index to included in the search.
Raise an error if there is no n-th occurrence of `s` or `s` is empty.
"""
var i = (offset_to_index(offset) + 1) - s._size


### Classes With Multiple `Pointer` Fields

If a class has more than one `Pointer` field then all of those fields must be handled by the custom serialisation and deserialisation methods for that class; there are not methods for each field. For example, if a class has three `Pointer` fields then the `_serialise_space()` method must return the total number of bytes required to serialise the objects from all three fields.


fun sctp_cc_opt_steady_step():I32 => @pony_os_sockopt_option(I32(562))
fun sctp_cc_opt_use_dccc_ecn():I32 => @pony_os_sockopt_option(I32(563))
fun sctp_cc_rfc2581():I32 => @pony_os_sockopt_option(I32(564))
fun sctp_cc_rtcc():I32 => @pony_os_sockopt_option(I32(565))
fun sctp_closed():I32 => @pony_os_sockopt_option(I32(566))
fun sctp_clr_stat_log():I32 => @pony_os_sockopt_option(I32(567))
fun sctp_cmt_base():I32 => @pony_os_sockopt_option(I32(568))
fun sctp_cmt_max():I32 => @pony_os_sockopt_option(I32(569))
fun sctp_cmt_mptcp():I32 => @pony_os_sockopt_option(I32(570))
fun sctp_cmt_off():I32 => @pony_os_sockopt_option(I32(571))
fun sctp_cmt_on_off():I32 => @pony_os_sockopt_option(I32(572))
fun sctp_cmt_rpv1():I32 => @pony_os_sockopt_option(I32(573))
fun sctp_cmt_rpv2():I32 => @pony_os_sockopt_option(I32(574))
fun sctp_cmt_use_dac():I32 => @pony_os_sockopt_option(I32(575))
fun sctp_connect_x():I32 => @pony_os_sockopt_option(I32(576))
fun sctp_connect_x_complete():I32 => @pony_os_sockopt_option(I32(577))
fun sctp_connect_x_delayed():I32 => @pony_os_sockopt_option(I32(578))
fun sctp_context():I32 => @pony_os_sockopt_option(I32(579))
fun sctp_cookie_ack():I32 => @pony_os_sockopt_option(I32(580))
fun sctp_cookie_echo():I32 => @pony_os_sockopt_option(I32(581))


fun box i16_unsafe()
: I16 val

Returns¶

I16 val

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

Returns¶

I32 val

i64_unsafe¶
[Source]


fun box dccp_sockopt_packet_size()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

dccp_sockopt_qpolicy_txqlen¶
[Source]


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


fun take_while(f: {(this->A!): Bool} box): List[this->A!]^ =>
"""
Builds a `List` of elements satisfying the predicate, stopping at the first `false` return.

```pony
let my_list = List[String].from(["a"; "b"; "c"])
let other_list = my_list.take_while( {(s: String): Bool => s < "b"} )  // ["a"]
```
"""
let l = List[this->A!]

if size() > 0 then
try
var node = head()?

for i in Range(0, size()) do
let item = node()?
if f(item) then l.push(item) else return l end
node = node.next() as this->ListNode[A]
end


# A text editor

While you can write code using any editor, it's nice to use one with some support for the language. We maintain a list of [editors supporting Pony](https://github.com/ponylang/ponyc/blob/main/EDITORS.md).


key: this->K!

Returns¶

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

next_index¶
[Source]
Given an index, return the next index that has a populated key and value.
Raise an error if there is no next populated index.
fun box next_index(
prev: USize val = call)
: USize val ?

Parameters¶

prev: USize val = call


"""
var buf = recover String end
var first = true
for v in data do
if first then
first = false
else
buf = (consume buf)._append(this)
end
buf.append(v.string())
end
buf

fun compare(that: String box): Compare =>
"""
Lexically compare two strings.
"""
compare_sub(that, _size.max(that._size))

fun compare_sub(


Returns¶

Bool val

lt¶
fun box lt(
y: F64 val)
: Bool val

Parameters¶

y: F64 val

Returns¶

Bool val


Here, we have two constructors, one that creates a `Wombat` that isn't hungry, and another that creates a `Wombat` that might be hungry or might not. Unlike some other languages that differentiate between constructors with method overloading, Pony won't presume to know which alternate constructor to invoke based on the arity and type of your arguments. To choose a constructor, invoke it like a method with the `.` syntax:

```pony
let defaultWombat = Wombat("Fantastibat") // Invokes the create method by default
let hungryWombat = Wombat.hungry("Nomsbat", 12) // Invokes the hungry method
```

__What's with the single quote thing, i.e. name'?__ You can use single quotes in parameter and local variable names. In mathematics, it's called a _prime_, and it's used to say "another one of these, but not the same one". Basically, it's just convenient.

Every constructor has to set every field in an object. If it doesn't, the compiler will give you an error. Since there is no `null` in Pony, we can't do what Java, C# and many other languages do and just assign either `null` or zero to every field before the constructor runs, and since we don't want random crashes, we don't leave fields undefined (unlike C or C++).

Sometimes it's convenient to set a field the same way for all constructors.

```pony
class Wombat
let name: String
var _hunger_level: U64
var _thirst_level: U64 = 1

new create(name': String) =>


let hard_links: U32 val¶
[Source]
Number of hardlinks to this filepath.

let device: U64 val¶
[Source]
OS id of the device containing this filepath.
Device IDs consist of a major and minor device id,
denoting the type of device and the instance of this type on the system.

let inode: U64 val¶
[Source]
UNIX specific INODE number of filepath. Is 0 on Windows.

let uid: U32 val¶
[Source]
UNIX-style user ID of the owner of filepath.

let gid: U32 val¶


(2, Generators.u8().filter({(u) => (u, (u % 2) != 0 }))
])
```
"""

// nasty hack to avoid handling the theoretical error case where we have
// no generator and thus would have to change the type signature
Generator[T](
object is GenObj[T]
fun generate(rnd: Randomness): GenerateResult[T] ? =>
let weight_sum: USize =
Iter[WeightedGenerator[T]](weighted_generators.values())
.fold[USize](
0,
// segfaults when types are removed - TODO: investigate
{(acc: USize, weighted_gen: WeightedGenerator[T]): USize^ =>
weighted_gen._1 + acc
})
let desired_sum = rnd.usize(0, weight_sum)
var running_sum: USize = 0


U128 val

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

Parameters¶

y: U128 val

Returns¶

(U128 val , U128 val)

div¶
[Source]


I64 val ?

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

Parameters¶

y: U64 val

Returns¶

I64 val

shr¶
[Source]


=>
"""
Assert that the given test function throws an error when run.
"""
try
test()?
fail(_format_loc(loc) + "Assert error failed. " + msg)
false
else
log(_format_loc(loc) + "Assert error passed. " + msg, true)
true
end

fun assert_no_error(
test: ITest box,
msg: String = "",
loc: SourceLoc = __loc)
: Bool
=>
"""


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


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


I64 val

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

Returns¶

I128 val

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

Returns¶


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


"""
Get a big-endian I32.
"""
u32_be()?.i32()

fun ref i32_le(): I32 ? =>
"""
Get a little-endian I32.
"""
u32_le()?.i32()

fun ref u64_be(): U64 ? =>
"""
Get a big-endian U64.
"""
let num_bytes = U64(0).bytewidth()
if _available >= num_bytes then
let node = _chunks.head()?
(var data, var offset) = node()?
if (data.size() - offset) >= num_bytes then


fun box rose_number_busy()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

rose_qbitincl¶
[Source]


OverheadBenchmark¶
[Source]
Default benchmark for measuring synchronous overhead.
class iso OverheadBenchmark is
MicroBenchmark iso

Implements¶

MicroBenchmark iso

Constructors¶
create¶


let range_bytes_gen = usize(0, range_bytes.size()-1)
.map[U8]({(size) =>
try
range_bytes(size)?
else
// should never happen
fallback
end })
byte_string(range_bytes_gen, min, max)

fun ascii_printable(
min: USize = 0,
max: USize = 100)
: Generator[String]
=>
"""
Create a generator for strings of printable ASCII characters,
with a minimum length of `min` (default: 0)
and a maximum length of `max` (default: 100).
"""


fun box bitwidth()
: U128 val

Returns¶

U128 val

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

Returns¶

USize val

min¶
[Source]


property¶
[Source]
fun ref property(
arg1: (T1 , T2 , T3),
h: PropertyHelper val)
: None val ?

Parameters¶

arg1: (T1 , T2 , T3)
h: PropertyHelper val

Returns¶

None val ?

property3¶
[Source]


y: U128 val

Returns¶

U128 val

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

Parameters¶

y: U128 val


fun box ipv6_recvpathmtu()
: I32 val

Returns¶

I32 val

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

Returns¶

I32 val

ipv6_recvrthdr¶
[Source]


A

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

Returns¶

A

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

Parameters¶


end
r

fun eq(that: HashSet[A, H] box): Bool =>
"""
Returns true if the sets contain the same elements.
"""
(size() == that.size()) and (this <= that)

fun ne(that: HashSet[A, H] box): Bool =>
"""
Returns false if the sets contain the same elements.
"""
not (this == that)

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


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


ForAll[T: T]¶
[Source]
class ref ForAll[T: T]

Constructors¶
create¶
[Source]
new ref create(
gen': Generator[T] val,
testHelper: TestHelper val)
: ForAll[T] ref^

Parameters¶