// KEKS -- Go KEKS codec implementation
// Copyright (C) 2024-2025 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program.  If not, see <http://www.gnu.org/licenses/>.

package keks

import "go.cypherpunks.su/keks/be"

func (ctx *Decoder) getStr(tag byte) (s string, err error) {
	l := int64(tag & 63)
	var ll int
	switch l {
	case 61:
		ll = 1
	case 62:
		ll = 2
		l += ((1 << 8) - 1)
	case 63:
		ll = 8
		l += ((1 << 8) - 1) + ((1 << 16) - 1)
	}
	if ll != 0 {
		s, err = ctx.getBytes(ll)
		if err != nil {
			return
		}
		ul := be.Get([]byte(s))
		if ul > (1<<63)-(63+((1<<8)-1)+((1<<16)-1)) {
			err = ErrLenTooBig
			return
		}
		l += int64(ul)
	}
	if ctx.opts != nil && ctx.opts.MaxStrLen > 0 && l > ctx.opts.MaxStrLen {
		err = ErrLenTooBig
		return
	}
	s, err = ctx.getBytes(int(l))
	if err != nil {
		return
	}
	return
}
