<?php

/**
 * Class Iobuffer 此类用来封装在网络通讯中字节流<br>
 * 此类提供了将int类型转换为byte数组 string转换为byte数组
 */
class Iobuffer
{
    /**
     * 最终的byte缓存数组
     */
    private $buf = array();
    /**
     * 当前数据在缓存数组中的位置
     */
    private $curPos;
    /**
     * 读取的数据在缓存数组中的位置
     */
    private $readPos;

    /**
     * 构造方法,初使化 curpos,readPos
     */
    public function __construct()
    {
        $this->curPos = 0;
        $this->readPos = 0;

    }
    /**
     * 返回一个byte数据 并且记录下当前所读数据的索引
     * @return
     */
    private function getByte()
    {
        return $this->buf[$this->readPos++];
    }

    public function putToBuf($data)
    {
        foreach ($data as $v)
        {
            $this->buf[]=$v;
            $this->curPos++;
        }
    }

    /**
     * 将int转为高位字节在前，低位字节在后的byte数组
     * @param $val 需要转换为byte数组的int值
     */
    private function intToByte($val)
    {

        $byt = array();
        $byt[0] = ($val >> 24 & 0xff);
        $byt[1] = ($val >> 16 & 0xff);
        $byt[2] = ($val >> 8 & 0xff);
        $byt[3] = ($val & 0xff);
        return $byt;
    }

    private function strToByte($str)
    {
        $len = strlen($str);
        $bytes = array();
        for($i=0;$i<$len;$i++) {
            if(ord($str[$i]) >= 128){
                $byte = ord($str[$i]) - 256;
            }else{
                $byte = ord($str[$i]);
            }
            $bytes[] =  $byte ;
        }
        return $bytes;
    }
    /**
     * 数据复位，清空
     */
    public function bufRest()
    {
        $temp_buf = array();
        $this->buf = $temp_buf;
        $this->curPos = 0;
        $this->readPos = 0;
    }
    /**
     * 把数据的长度放到缓存数组当中
     * @param $val
     */
    public function putIntToBuf($val)
    {
        $data = $this->intToByte($val);
        $this->putToBuf($data);
    }

    /**
     * 将缓存数组中前四个字节byte 转换为 int 数组中存放的是高位在前
     * @param data
     * @return
     */
    public function getInt()
    {
        $a = $this->getByte();
        $b = $this->getByte();
        $c = $this->getByte();
        $d = $this->getByte();

        $val = 0;
        $val = $a & 0xff;
        $val <<= 8;
        $val |= $b & 0xff;
        $val <<= 8;
        $val |= $c & 0xff;
        $val <<= 8;
        $val |= $d & 0xff;
        return $val;
    }

    /**
     * 将字符串先转换为byte数组然后放入到缓冲数组buf当中
     * @param $val
     */
    public function putStrToBuf($val)
    {
        $data = $this->strToByte($val);
        $this->putToBuf($data);
    }

    public function getStr()
    {
        $str = '';
        $bytes = $this->buf;
        foreach($bytes as $ch) {
            $str .= chr($ch);
        }

        return $str;
    }


    public function getBuf()
    {
        return $this->buf;
    }
    public function getBufSize()
    {
        return $this->curPos;
    }
}




?>