c3bfe1393d936d0b064b12b3054ecf125399e866
[uffi.git] / tests / strtol.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          strtol.lisp
6 ;;;; Purpose:       UFFI Example file to strtol, uses pointer arithmetic
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Feb 2002
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UFFI, is Copyright (c) 2002-2003 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; *************************************************************************
15
16 (in-package #:uffi-tests)
17
18 (uffi:def-foreign-type char-ptr (* :unsigned-char))
19   
20 ;; This example does not use :cstring to pass the input string since
21 ;; the routine needs to do pointer arithmetic to see how many characters
22 ;; were parsed
23
24 (uffi:def-function ("strtol" c-strtol) 
25     ((nptr char-ptr)
26      (endptr (* char-ptr))
27      (base :int))
28   :returning :long)
29
30 (defun strtol (str &optional (base 10))
31   "Returns a long int from a string. Returns number and condition flag.
32 Condition flag is T if all of string parses as a long, NIL if
33 their was no string at all, or an integer indicating position in string
34 of first non-valid character"
35   (let* ((str-native (uffi:convert-to-foreign-string str))
36          (endptr (uffi:allocate-foreign-object 'char-ptr))
37          (value (c-strtol str-native endptr base))
38          (endptr-value (uffi:deref-pointer endptr 'char-ptr)))
39
40     (unwind-protect
41          (if (uffi:null-pointer-p endptr-value)
42              (values value t)
43              (let ((next-char-value (uffi:deref-pointer endptr-value :unsigned-char))
44                    (chars-parsed (- (uffi:pointer-address endptr-value)
45                                     (uffi:pointer-address str-native))))
46                (cond
47                  ((zerop chars-parsed)
48                   (values nil nil))
49                  ((uffi:null-char-p next-char-value)
50                   (values value t))
51                  (t
52                   (values value chars-parsed)))))
53       (progn
54         (uffi:free-foreign-object str-native)
55         (uffi:free-foreign-object endptr)))))
56
57 (deftest strtol.1 (strtol "123") 123 t)
58 (deftest strtol.2 (strtol "0") 0 t)
59 (deftest strtol.3 (strtol "55a") 55 2)
60 (deftest strtol.4 (strtol "a") nil nil)
61
62
63                            
64