TeX has a \parshape primitive that specifies a number of special lines before a paragraph then for each line, a pair of (left margin, line width) pairs. The last pair is used on all following lines, so
\documentclass{article}
\setlength\textwidth{6cm}
\begin{document}
\newlength\shortline
\shortline=\dimexpr\textwidth-2cm
\parshape 4
0pt \shortline
0pt \shortline
0pt \shortline
0pt \textwidth
One two three four five six seven.
Red blue green yellow white black.
One two three four five six seven.
Red blue green yellow white black.
One two three four five six seven.
Red blue green yellow white black.
\end{document}
Produces

So basically wrapfig sets the figure in a box to find the default length to cut and the number of lines to cut so as to produce the above, then it drops in the figure in the space:
\documentclass{article}
\setlength\textwidth{6cm}
\newlength\shortline
\begin{document}
\shortline=\dimexpr\textwidth-2cm
\parshape 4
0pt \shortline
0pt \shortline
0pt \shortline
0pt \textwidth
\noindent\smash{\rlap{\hspace{\textwidth}\llap{%
\hspace{2mm}%
\rule[-.8cm]{1.8cm}{1cm}}}}%
\indent
One two three four five six seven.
Red blue green yellow white black.
One two three four five six seven.
Red blue green yellow white black.
One two three four five six seven.
Red blue green yellow white black.
\end{document}
Producing

The clever part of the package is detecting if you need more than one paragraph and if so constructing a new shorter \parshape for the later ones.
\documentclass{article}
\setlength\textwidth{6cm}
\newlength\shortline
\begin{document}
\sloppy
\shortline=\dimexpr\textwidth-2cm
\parshape 4
0pt \shortline
0pt \shortline
0pt \shortline
0pt \textwidth
\noindent\smash{\rlap{\hspace{\textwidth}\llap{%
\hspace{2mm}%
\rule[-.8cm]{1.8cm}{1cm}}}}%
\indent
One two three four five six seven.
Red blue green
\parshape 2
0pt \shortline
0pt \textwidth
Yellow white black.
One two three four five six seven.
Red blue green yellow white black.
One two three four five six seven.
Red blue green yellow white black.
\end{document}
