001/*
002 * Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation.
008 *
009 * This code is distributed in the hope that it will be useful, but WITHOUT
010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
011 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
012 * version 2 for more details (a copy is included in the LICENSE file that
013 * accompanied this code).
014 *
015 * You should have received a copy of the GNU General Public License version
016 * 2 along with this work; if not, write to the Free Software Foundation,
017 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
018 *
019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
020 * or visit www.oracle.com if you need additional information or have any
021 * questions.
022 */
023package com.oracle.graal.compiler.common.util;
024
025/**
026 * Provides low-level sequential write access for signed and unsigned values of size 1, 2, 4, and 8
027 * bytes.
028 */
029public interface TypeWriter {
030
031    /**
032     * Returns the number of bytes that have been written, i.e., the byte index of the next byte to
033     * be written.
034     */
035    long getBytesWritten();
036
037    /** Writes a signed 1 byte value. */
038    void putS1(long value);
039
040    /** Writes an unsigned 1 byte value. */
041    void putU1(long value);
042
043    /** Writes a signed 2 byte value. */
044    void putS2(long value);
045
046    /** Writes an unsigned 2 byte value. */
047    void putU2(long value);
048
049    /** Writes a signed 4 byte value. */
050    void putS4(long value);
051
052    /** Writes an unsigned 4 byte value. */
053    void putU4(long value);
054
055    /** Writes a signed 8 byte value. */
056    void putS8(long value);
057
058    /**
059     * Writes a signed value in a variable byte size encoding.
060     */
061    default void putSV(long value) {
062        long cur = value;
063        while (true) {
064            if (cur >= -64 && cur < 64) {
065                putU1(cur & 0x7f);
066                return;
067            }
068            putU1(0x80 | (cur & 0x7f));
069            cur = cur >> 7;
070        }
071    }
072
073    /**
074     * Writes an unsigned value in a variable byte size encoding.
075     */
076    default void putUV(long value) {
077        long cur = value;
078        while (true) {
079            assert cur >= 0;
080            if (cur < 128) {
081                putU1(cur & 0x7f);
082                return;
083            }
084            putU1(0x80 | (cur & 0x7f));
085            cur = cur >> 7;
086        }
087    }
088}