examples/gallery/13-lease.hero
Passare a una libreria C un testo che quella terrà, e dire quando si è finito.
- 27 righe
- usa C:
13-lease.h
Una stringa prestata con .cstr() è del C per una chiamata sola, e alcune librerie tengono il puntatore e lo leggono dopo. L’header non può dire quali, quindi lo dice il programma: x: cstr @= s.lease() consegna al C una copia dei byte in lease, cioè in prestito finché lo dici tu: la copia vive finché end_lease(@x) la libera e lascia x vuota. Nient’altro può scrivere x, e il suo nome può stare solo come argomento di una chiamata, così un secondo end_lease la trova vuota e ferma il programma invece di liberare due volte.
Un lease che nessuno chiude ferma il programma quando main termina, dicendo quanti ne restano aperti. Il lato C, qui, è la più piccola libreria che tiene ciò che riceve, 13-lease.h, mostrato qui sotto. Nel repository sta già accanto al programma; se copi il programma altrove, porta con te anche l’header.
Eseguilo
Questo esempio serve a illustrare il linguaggio. Qui trovi il programma e non un risultato: non ci sono ancora test che confrontino il suo output byte per byte.
Il programma
## Text a C library keeps
#
# `s.cstr()` lends a string to C for one call, and the bytes may be gone by the
# next line. Some libraries keep the pointer and read it later — SQLite when it
# is told not to copy, libcurl for the body of a request — and the header cannot
# say which: a parameter that copies and one that keeps are both `const char *`.
#
# A lease is for that case. `x: cstr @= s.lease()` hands C a COPY of the bytes
# that lives until `end_lease(@x)` frees it and empties the cell. The name of a
# lease may stand only as an argument of a call, nothing else writes its cell,
# and a lease nobody ends is counted when `main` returns, so a leak is a loud
# exit rather than a silent one. The C side here is the smallest library that
# keeps what it is given: `13-lease.h`, beside this file.
extern "13-lease.h"
function keep_label(s: cstr)
function kept_label_length() -> u64
function main()
at: i64 @= 0
while at < 3
label: cstr @= f"row-{at}-payload".lease()
keep_label(s: label)
print(f"C still reads {kept_label_length()} bytes")
end_lease(@label)
at @ at + 1
Il lato C
/* A C side that KEEPS the text it is handed and reads it later. Libraries do
* this — SQLite's SQLITE_STATIC, libcurl's CURLOPT_POSTFIELDS — and the header
* cannot say so: both a copying and a keeping parameter are `const char *`. */
#include <string.h>
static const char *label_kept_by_c;
static inline void keep_label(const char *s) { label_kept_by_c = s; }
static inline size_t kept_label_length(void) { return strlen(label_kept_by_c); }
impronta sha256 5ff3ca27b965 · 2 file · index.json
Successivo: calculator. Tutti gli esempi. ← Precedente: 12-interpolation
Eseguine uno: i quattro comandi. Impara il linguaggio, oppure leggi la specifica completa in un solo file.