diff --git a/include/pocketpy/str.h b/include/pocketpy/str.h index e303c91f..7debedba 100644 --- a/include/pocketpy/str.h +++ b/include/pocketpy/str.h @@ -148,7 +148,7 @@ struct SStream{ SStream& operator<<(char); SStream& operator<<(StrName); - void write_hex(unsigned char); + void write_hex(unsigned char, bool non_zero=false); void write_hex(void*); void write_hex(i64); }; diff --git a/src/str.cpp b/src/str.cpp index b252b258..cdbb8e45 100644 --- a/src/str.cpp +++ b/src/str.cpp @@ -521,33 +521,48 @@ int utf8len(unsigned char c, bool suppress){ return *this; } - void SStream::write_hex(unsigned char c){ - *this << "0123456789ABCDEF"[c >> 4]; - *this << "0123456789ABCDEF"[c & 0xf]; + void SStream::write_hex(unsigned char c, bool non_zero){ + unsigned char high = c >> 4; + unsigned char low = c & 0xf; + if(non_zero){ + if(high) (*this) << "0123456789abcdef"[high]; + if(high || low) (*this) << "0123456789abcdef"[low]; + }else{ + (*this) << "0123456789abcdef"[high]; + (*this) << "0123456789abcdef"[low]; + } } void SStream::write_hex(void* p){ + if(p == nullptr){ + (*this) << "0x0"; + return; + } (*this) << "0x"; uintptr_t p_t = reinterpret_cast(p); + bool non_zero = true; for(int i=sizeof(void*)-1; i>=0; i--){ unsigned char cpnt = (p_t >> (i * 8)) & 0xff; - write_hex(cpnt); + write_hex(cpnt, non_zero); + if(cpnt != 0) non_zero = false; } } void SStream::write_hex(i64 val){ + if(val == 0){ + (*this) << "0x0"; + return; + } if(val < 0){ (*this) << "-"; val = -val; } (*this) << "0x"; - if(val == 0){ - (*this) << "0"; - return; - } + bool non_zero = true; for(int i=56; i>=0; i-=8){ unsigned char cpnt = (val >> i) & 0xff; - if(cpnt != 0) write_hex(cpnt); + write_hex(cpnt, non_zero); + if(cpnt != 0) non_zero = false; } } diff --git a/tests/04_str.py b/tests/04_str.py index bc820c50..79cc89cb 100644 --- a/tests/04_str.py +++ b/tests/04_str.py @@ -183,5 +183,25 @@ stack=[1,2,3,4]; assert f"{stack[2:]}" == '[3, 4]' assert repr('\x1f\x1e\x1f') == '\'\\x1f\\x1e\\x1f\'' -assert hex(255) == '0xFF' -assert hex(-42) == '-0x2A' + +assert hex(-42) == '-0x2a' +assert hex(42) == '0x2a' + +assert hex(0) == '0x0' +assert hex(1) == '0x1' +assert hex(15) == '0xf' +assert hex(16) == '0x10' +assert hex(255) == '0xff' +assert hex(256) == '0x100' +assert hex(257) == '0x101' +assert hex(17) == '0x11' + +import c +assert repr(c.NULL) == '' +assert repr(c.void_p(1)) == '' +assert repr(c.void_p(15)) == '' +assert repr(c.void_p(16)) == '' +assert repr(c.void_p(255)) == '' +assert repr(c.void_p(256)) == '' +assert repr(c.void_p(257)) == '' +assert repr(c.void_p(17)) == ''