Give me the position within a rectangle closest to another position. It's complicated but can you do it? :D

We have a rectangle.

The position is 0,0,0 of this rectangle
the size is 3 x 3 x 3

We have another position 0, 3, 1

The nearest position of this rectangle to 0, 3, 1 within the boundary of the rectangle is
0, 1.5, 1

image
The red part is the ‘nearest’ position within the rectangle.
The white part is the position.
The green is the rectangle boundary

I need a function that gives me the nearest position to another given position within a rectangle please! :(((

other examples
image
image

local function constrain(pos,targ,size)
	local halfsize = size/2
	local add,sub = pos+halfsize,pos-halfsize
	if targ>add then
		return add
	elseif targ<sub then
		return sub
	end
	return targ
end
local function constrainV3(pos,targ,size)
	targ = pos + (CFrame.new(pos,targ).LookVector.Unit*size)
	return Vector3.new(constrain(pos.X,targ.X,size.X),constrain(pos.Y,targ.Y,size.Y),constrain(pos.Z,targ.Z,size.Z))
end

should be pretty self explainatory,
pos = green part position
targ = grey part position
size = green part size

*this isn’t going to be completely accurate + dont ask me how it works + there is a better way using linear algebra which i couldnt be bothered to code (: