;;;;
;;;; test-ffi.stk   -- Tests of FFI
;;;;
;;;; Copyright © 2007-2024 Erick Gallesio <eg@stklos.net>
;;;;
;;;;
;;;; This program is free software; you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation; either version 2 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with this program; if not, write to the Free Software
;;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
;;;; USA.
;;;;
;;;;           Author: Erick Gallesio [eg@essi.fr]
;;;;    Creation date: 26-Sep-2009 10:17 (eg)
;;;;
(require "test")

(test-section "FFI")

;;; RINDEX
(define-external %rindex (:string :int)
  :entry-name "strrchr"
  :return-type :string)

(define (rindex str char)
  (%rindex str (char->integer char)))

;;; STRLEN
(define-external strlen(:string)
  :return-type :int)


(test "rindex.1"
      "/d"
      (rindex "/a/b/c/d" #\/))


(test "rindex.2"
      (void)
      (rindex "/a/b/c/d" #\A))

(test "strlen.1"
      0
      (strlen ""))

(test "strlen.2"
      5
      (strlen "abcde"))

;;; COS

(define-external cos(:double)
  :return-type :double)

;; check that we actually shadowed the original 'cos' in Scheme:
(test "cos.1"
      #f
      (eq? cos (in-module SCHEME cos)))

(test "cos.2"
      #t
      (= (cos 1.5)
         ((in-module SCHEME cos) 1.5)))

;;; ABS, LABS

(define-external labs(:int)
  :return-type :int)

(define-external abs(:long)
  :return-type :long)

(test "abs.1"
      #f
      (eq? abs (in-module SCHEME abs)))

(test "abs.2"
      200
      (abs -200))

(test "abs.3"
      200
      (abs 200))

(test "abs.4"
            #t
            (= (abs -65)
               ((in-module SCHEME abs) -65)))

;; if we don't restore abs, it will cause errors later. Our Scheme abs works for
;; reals, but the C abs is for ints only...
(define abs (in-module SCHEME abs))

(test "labs.1"
      200
      (labs -200))

(test "labs.2"
      200
      (labs 200))

(test "labs.3"
            #t
            (= (labs -65)
               ((in-module SCHEME abs) -65)))

;;; NULL pointer and STRTOL

;; Suppressed by eg 
;; (test "null cpointer" #t (cpointer-null? (%make-cpointer-null)))

(define-external strtol(:string :pointer :int)
  :return-type :long)

;; base 8
(test "strtol.1"
      513
      (strtol "1001" #void 8))

;; base 10
(test "strtol.2"
      1001
      (strtol "1001" #void 10))

;; base 2
(test "strtol.3"
      9
      (strtol "1001" #void 2))

;; base 16
(test "strtol.4"
      6699
      (strtol "1a2b" #void 16))



(test-section-end)
