std::ffi::c::int (v0.2.2)

Raw C bindings for integer text conversion.

Latest

Overview

std::ffi::c::int exposes C conversion functions such as atoi, strtol, strtoll, strtoul, and strtoull.

These return raw C results; check the end pointer or errno when conversion can fail.

Source: thrustc/std/v0.2.2/ffi/c/int.thrust

Public Signatures

Exported declarations for this module snapshot.

fn atoi(text: CString)                                  s32 @public @extern("atoi")    @convention("C");
fn atol(text: CString)                                  s64 @public @extern("atol")    @convention("C");
fn atoll(text: CString)                                 s64 @public @extern("atoll")   @convention("C");
fn strtol(text: CString, end: ptr[ptr], base: s32)      s64 @public @extern("strtol")  @convention("C");
fn strtoll(text: CString, end: ptr[ptr], base: s32)     s64 @public @extern("strtoll") @convention("C");
fn strtoul(text: CString, end: ptr[ptr], base: s32)     u64 @public @extern("strtoul") @convention("C");
fn strtoull(text: CString, end: ptr[ptr], base: s32)    u64 @public @extern("strtoull") @convention("C");

Behavior and Use

The conversion functions return raw C results and may set errno on failure.

Check the end pointer or errno when a conversion can fail.

Examples

import std::ffi::c::int as c;

// atoi is raw and simple. Wrap it when the surrounding code only needs a
// small, trusted decimal value.
fn readWorkers(text: CString) s32 @public {
    var workers: s32 = c::atoi(text);

    if workers < 1 {
        return 1;
    }

    return workers;
}
import std::ffi::c::int as c;

// strtol lets the wrapper choose the numeric base at the boundary.
fn parsePort(text: CString) s32 @public {
    var end: ptr = nullptr;
    var value: s64 = c::strtol(text, ref end, 10);

    if end == (text as ptr) {
        return 0;
    }

    if value < 0 {
        return 0;
    }

    if value > 65535 {
        return 65535;
    }

    return value as s32;
}
import std::ffi::c::int as c;

// Keep hexadecimal parsing in one helper so callers do not repeat raw C calls.
fn parseColorChannel(text: CString) u32 @public {
    var end: ptr = nullptr;
    var value: u64 = c::strtoul(text, ref end, 16);

    if end == (text as ptr) {
        return 0;
    }

    if value > 255 {
        return 255;
    }

    return value as u32;
}

Notes

Back to std index