;;; Gash -- Guile As SHell
;;; Copyright © 2019 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;; Copyright © 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;
;;; This file is part of Gash.
;;;
;;; Gash 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 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Gash 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 Gash.  If not, see <http://www.gnu.org/licenses/>.

;; Copyright © 2010, 2012 Göran Weinholt <goran@weinholt.se>

(define-module (rnrs compat)
  #:use-module (ice-9 binary-ports)
  #:use-module (ice-9 receive)
  #:export (assert
            bitwise-and
            bitwise-bit-field
            bitwise-length
            call-with-bytevector-output-port
            call-with-string-output-port
            list-sort
            div
            mod
            open-file-input-port
            port-eof?
            port-position
            set-port-position!))

(define-syntax assert
  (syntax-rules ()
    ((_ expression)
     (or expression
         (throw 'assert (format #f "assertion failed: ~s" 'expression))))))

(define bitwise-and logand)
(define bitwise-length integer-length)
(define bitwise-bit-field bit-extract)

(define (call-with-port port proc)
  "Call @var{proc}, passing it @var{port} and closing @var{port} upon exit of
@var{proc}.  Return the return values of @var{proc}."
  (call-with-values
      (lambda () (proc port))
    (lambda vals
      (close-port port)
      (apply values vals))))

(define* (call-with-bytevector-output-port proc #:optional (transcoder #f))
  (receive (port extract) (open-bytevector-output-port transcoder)
    (call-with-port port proc)
    (extract)))

(define (call-with-string-output-port procedure)
  (call-with-output-string procedure))

(define (list-sort proc list)
  (stable-sort list proc))

(define mod modulo)
(define div quotient)

(define (open-file-input-port file-name)
  (open-input-file file-name))

(define (port-eof? port)
  (eof-object? (lookahead-u8 port)))

(define (port-position port)
  (ftell port))

(define (set-port-position! port pos)
  (seek port pos SEEK_SET))
