--- parser3/src/classes/hash.C 2024/10/02 17:58:15 1.165 +++ parser3/src/classes/hash.C 2024/11/04 03:53:25 1.168 @@ -1,7 +1,7 @@ /** @file Parser: @b hash parser class. - Copyright (c) 2001-2023 Art. Lebedev Studio (http://www.artlebedev.com) + Copyright (c) 2001-2024 Art. Lebedev Studio (http://www.artlebedev.com) Authors: Konstantin Morshnev , Alexandr Petrosian */ @@ -18,7 +18,7 @@ #include "pa_vbool.h" #include "pa_vmethod_frame.h" -volatile const char * IDENT_HASH_C="$Id: hash.C,v 1.165 2024/10/02 17:58:15 moko Exp $"; +volatile const char * IDENT_HASH_C="$Id: hash.C,v 1.168 2024/11/04 03:53:25 moko Exp $"; // class @@ -572,8 +572,6 @@ static void _at(Request& r, MethodParams HashStringValue& hash=GET_SELF(r, VHashBase).hash(); size_t count=hash.count(); - int pos=0; - // misha@ // I do not like that type is checked before whence. // But I do not like the idea to move it after whence (where process can be called) even more. @@ -588,20 +586,7 @@ static void _at(Request& r, MethodParams throw Exception(PARSER_RUNTIME, &stype, "type must be 'key', 'value' or 'hash'"); } - Value& vwhence=params[0]; - if(vwhence.is_string()) { - const String& swhence=*vwhence.get_string(); - if(swhence == "last") - pos=count-1; - else if(swhence != "first") - throw Exception(PARSER_RUNTIME, - &swhence, - "whence must be 'first', 'last' or expression"); - } else { - pos=r.process(vwhence).as_int(); - if(pos < 0) - pos+=count; - } + int pos=params.as_index(0, count, r); if(count && pos >= 0 && (size_t)pos < count){ switch(result_type) { @@ -663,6 +648,33 @@ static void _at(Request& r, MethodParams } } +static void _set(Request& r, MethodParams& params) { + HashStringValue& hash=GET_SELF(r, VHashBase).hash(); + size_t count=hash.count(); + + int pos=params.as_index(0, count, r); + + if(count && pos >= 0 && (size_t)pos < count){ +#ifdef HASH_ORDER + if((size_t)pos == count-1) { + hash.last_pair()->value=&r.process(params[1]); + return; + } else +#endif + { + for(HashStringValue::Iterator i(hash); i; i.next(), pos-- ) + if(!pos){ + i.pair()->value=&r.process(params[1]); + return; + } + } + } + + if(count) + throw Exception(PARSER_RUNTIME, 0, "index '%d' is out of range 0..%d", pos, count-1); + throw Exception(PARSER_RUNTIME, 0, "index '%d' is out of range: hash is empty", pos); +} + extern String table_reverse_name; static void _select(Request& r, MethodParams& params) { @@ -841,9 +853,13 @@ MHash::MHash(): Methoded("hash") add_native_method("reverse", Method::CT_DYNAMIC, _reverse, 0, 0); // ^hash._at[first|last[;'key'|'value'|'hash']] - // ^hash._at([-+]offset)[['key'|'value'|'hash']] + // ^hash._at([-+]index)[['key'|'value'|'hash']] add_native_method("_at", Method::CT_DYNAMIC, _at, 1, 2); + // ^hash.set[first|last;value] + // ^hash.set([-+]index)[value] + add_native_method("set", Method::CT_DYNAMIC, _set, 2, 2); + // ^hash.rename[from;to] // ^hash.rename[ $.from[to] ... ] add_native_method("rename", Method::CT_DYNAMIC, _rename, 1, 2);