Skip to content

Commit

Permalink
Implement encoding and decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
ben221199 committed Nov 18, 2023
1 parent 917758b commit 2c2cd6e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 8 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
],
"license": "GPL-3.0-or-later",
"require": {
"php": "^7||^8",
"php": "^7||^8"
},
"require-dev": {
"phpunit/phpunit": "^7||^8||^9"
Expand Down
50 changes: 44 additions & 6 deletions src/Netstring.php
Original file line number Diff line number Diff line change
@@ -1,22 +1,60 @@
<?php
namespace YOCLIB\Netstring;

use Exception;

class Netstring{

private $string;
/**
* @var int $maxLength
*/
private static $maxLength = 2000000;

/**
* @return int
*/
public static function getMaxLength(){
return self::$maxLength;
}

/**
* @param $maxLength
* @return void
*/
public static function setMaxLength($maxLength){
self::$maxLength = $maxLength;
}

/**
* @return string
* @throws Exception
*/
public function getString(){
return $this->string;
public static function decode($string){
$length = explode(':',$string,2)[0] ?? null;
if($length==null){
throw new Exception('Netstring does not have a semicolon.');
}
$semicolon = $string[strlen($length)] ?? null;
if($semicolon!=':'){
throw new Exception('Expecting semicolon. Was \''.$semicolon.'\'.');
}
$data = substr($string,strlen($length)+1,intval($length));
$comma = $string[strlen($length)+1+intval($length)] ?? null;
if($comma!=','){
throw new Exception('Expecting comma. Was \''.$comma.'\'.');
}
return $data;
}

/**
* @param string string
* @return string
* @throws Exception
*/
public function setString($string): void{
$this->string = $string;
public static function encode($string){
if(strlen($string)>self::$maxLength){
throw new Exception('Length of '.strlen($string).' exceeding '.self::$maxLength.' during encoding.');
}
return strlen($string).':'.$string.',';
}

}
16 changes: 15 additions & 1 deletion tests/NetstringTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,20 @@

class NetstringTest extends TestCase{

//TODO Create tests
public function testDecodingNetstring(){
self::assertEquals('',Netstring::decode('0:,'));
self::assertEquals('a',Netstring::decode('1:a,'));
self::assertEquals('ab',Netstring::decode('2:ab,'));
self::assertEquals('abc',Netstring::decode('3:abc,'));
self::assertEquals('abcd',Netstring::decode('4:abcd,'));
}

public function testEncodingNetstring(){
self::assertEquals('0:,',Netstring::encode(''));
self::assertEquals('1:a,',Netstring::encode('a'));
self::assertEquals('2:ab,',Netstring::encode('ab'));
self::assertEquals('3:abc,',Netstring::encode('abc'));
self::assertEquals('4:abcd,',Netstring::encode('abcd'));
}

}

0 comments on commit 2c2cd6e

Please sign in to comment.