PHP function Manual (Homemade binary "database")

Source: Internet
Author: User
Tags format definition fread unpack

Introduction

Pack, unpack function, if there is no contact with the socket, this may be unfamiliar, these two functions in the socket interaction is a group package, the data loaded into a binary string, and the binary string data in the unpacking, there are many formats, Specific format can go to the official manual (or after reading this article, to call the interface to see), I mainly use the pack ("n", int), pack ("a", str) and their two corresponding unpacking function, N in the manual explanation is the following, accounting for 4 bytes, The big-endian way (in fact, is the low in front or after the problem). A is a string to be packaged, not enough to specify the value of the time with null (or Assic code 0 corresponding to the character) padding.

N-unsigned long (always the bit, big endian byte order)

a-nul-padded string

I will use this package unpacking function to do a function manual query gadget, or can be said to be a homemade small binary database.

Design data formats

In doing this binary file database I will create two files, one is the index file, one is to query the data of the file, see their structure separately:

The number in parentheses in the description is the number of bytes (bytes), and the "~" wavy lines indicate that the number of bytes is indeterminate

Data file, the first PHP is a formal string "PHP", accounting for 4 bytes, followed by the version description, length is indeterminate (this length can be obtained from the index file later), followed by the main store information. The first is a function name length lenname accounted for 4 bytes, followed by the function name, the length is indeterminate, there is the previous Lenname corresponding value determination, followed by the Lenval accounted for 4 bytes, followed by the specific function description content, the length of the previous lenval corresponding value determination.

          Content storage format definition ++++++++++++++++++++++++++++++++++++++|php (4)        | Release Notes (~)           |+++++++++++++++ +++++++++++++++++++++++|lenname (4)    | function name (~)           |++++++++++++++++++++++++++++++++++++++|lenval ( 4)     | function contents (~)           |++++++++++++++++++++++++++++++++++++++             ...

index files, the index files are simpler, all of which store the position of the pointer at the beginning of each function in the storage file above, each occupying 4 bytes.

index format definition ++++++++++++++++++++++++++++++++++++++|position (4)                         |+++++++++++++++++++++++++ +++++++++++++            ......

Implementation of the query

Since the contents of the stored file are stored in the order of the function names, the indexes are stored in the order in which they are stored, so it is convenient to obtain them directly using the binary method, so that the desired functions can be easily obtained.

The following methods are used primarily when querying:

First, get the value of an index from the set position (that is, the corresponding function stores the pointer position of the file)

 /*  * * Gets the location of a record from the index file * @param the starting position in the index file, Gets four bytes from the starting position for the start of a function description * @return Returns the storage location pointer offset for the index position  */ private  function  _getoneindex ( $pos   fseek  ( $this ->_indexhandle,  $pos  );   $len  = unpack  ("Nlen", fread  ( $this ->_indexhandle, 4 return   $len  [' Len ' ];}

Second, get the contents of a Len (4) +val (~) format from the specified pointer offset position

/** * Get a len+val content from the set pointer offset * @param the pointer offset of the $pos file * @return Returns an array, including length and value*/Private function_getstorelenvalformat ($pos){    fseek($this->_storehandle,$pos); $len=Unpack("Nlen",fread($this->_storehandle, 4)); $len=$len[' Len ']; $val=fread($this->_storehandle,$len); return Array    (        ' Len ' =$len, ' value ' =$val,    );}

Third, get the description of the development function, this is also the most important part, using the dichotomy method to get a record from the data file

/** * Get function Contents * @param the function name to find * @return The JSON string that returns the function description*/ Public functionGet$func){    if(!$this-isinit ())return; $begin= 0; $end=filesize($this->_indexfile)/4; $ret= ' [] ';  while($begin<$end){        $mid= Floor(($begin+$end)/2); $pos=$mid*;//$mid just the position of the pointer variable, and the length of the pointer must be multiplied by 4$pos=$this->_getoneindex ($pos); $name=$this->_getstorelenvalformat ($pos); $flag=strcmp($func,$name[' Value ']); if($flag= = 0){            $val=$this->_getstorelenvalformat ($pos+4+$name[' Len ']); $ret=$val[' Value '];  Break; }ElseIf($flag< 0){            $end=$end==$mid?$mid-1:$mid; }Else{            $begin=$begin==$mid?$mid+1:$mid; }    }    return $ret;}

It's easy to use, just include the class library file and store the file database, and then call a few lines of code to

<? PHP include_once ("./manual/phpmanual.php"); $t New phpmanual (); $t->init (' zh '); Echo $t->get ("unpack");

The output is a JSON string, converted as follows, with detailed explanations and concise examples

{    "Name": "Unpack",    "desc": "Unpack data from binary string.",    "Long_desc": "Unpacks from a binary string into an array according to the given ' format '. \\n\\nThe unpacked data is stored In an associative array. To accomplish this is the different format codes and separate them by a slash/. If a repeater argument is present and then each of the array keys would have a sequence number behind the given name. ",    "ver": "PHP 4, PHP 5",    "Ret_desc": "Returns an associative array containing unpacked elements of binary string.",    "Seealso": [        "Pack"    ],    "url": "Function.unpack",    "Class":NULL,    "Params": [        {            "List": [                {                    ' Type ': ' String ',                    "var": "$format",                    "Beh": 0,                    "desc": "See Pack () for the explanation of the format codes."                },                {                    ' Type ': ' String ',                    "var": "$data",                    "Beh": 0,                    "desc": "The packed data."                }            ],            "Ret_type": "Array"        }    ],    "Examples": [        {            "title": "Unpack () example",            "Source": "$binarydata = \" \\x04\\x00\\xa0\\x00\ "; \n$array = unpack (\" cchars/nint\ ", $binarydata);",            "Output":NULL        },        {            "title": "Unpack () example with a repeater",            "Source": "$binarydata = \" \\x04\\x00\\xa0\\x00\ "; \n$array = unpack (\" c2chars/nint\ ", $binarydata);",            "Output":NULL        },        {            "title": "Unpack () example with unnamed keys",            "Source": "$binarydata = \" \\x32\\x42\\x00\\xa0\ "; \n$array = unpack (\" c2/n\ ", $binarydata); \nvar_dump ($array);",            "Output":NULL        }    ]}

Finally, we enclose the directory structure:

+phpmanual    +manual        +phpmanual            +zh                |  _manualindex                | _manualstore        | _phpmanual.php    | _test.php

This is the full address of the program:

Full Example Address

Reference

Https://github.com/aizuyan/php-doc-parser all the data from this phpmanual.

  

The copyright belongs to the author Iforever ([email protected]) all, without the author's consent to prohibit any form of reprint, reproduced article must be in the article page obvious location to the author and the original text connection, otherwise reserve the right to pursue legal responsibility.

PHP function Manual (Homemade binary "database")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.